我正在编写一个执行一些简单的tcp通信的程序,但我对c / c ++的说法不太精确。
我的问题
当我将 stdin 中的数据放入带public class AttractiveAdapter extends ArrayAdapter<AttractivePlaces> {
private List<AttractivePlaces> mDataset = new ArrayList<>();
private Context context;
public class AttractiveAdapter (Context context) {
this.context = context;
}
// Here you can freely change the dataset on user click
public void changeDataset (List<AttractivePlaces> newItems) {
if(mDataset.size() > 0){
mDataset.clear();
}
mDataset.addAll(newItems);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
...
// Check whether the picture is or not.
if (city.hasImage()) {
//
image.setImageResource(mDataset.get(position).getmAttaticePlaceImageResourceId());
} else {
image.setVisibility(View.GONE);
}
@Override
public int getCount() {
return mDataset.size();
}
}
的缓冲区(char数组)时,它可以正常工作。
当我尝试将数据从字符串放入带有fgets()
的同一缓冲区时,似乎在我打印缓冲区时工作 - 但是我遇到了问题。
工作fgets()示例:
strncpy()
strncpy()失败示例:
int messageSize = 256;
char buffer[messageSize];
bzero(buffer, messageSize);
fgets(buffer, messageSize, stdin);
printf("%s\n", buffer); // seems good, prints out whatever I send in stdin
// passing the buffer on, no problems
为什么在使用int messageSize = 256;
char buffer[messageSize];
bzero(buffer, messageSize);
strncpy(buffer, mystring.c_str(), messageSize);
printf("%s\n", buffer); // seems good, prints out whatever the string was
// passing the buffer on and I get problems
代码时遇到问题,如果我在 stdin 中传递字符串,结果是否相同?
我遇到的问题:
当在此处传递缓冲区时会发生以下情况:
strncopy()
使用// we just put data into the buffer
n = write(sockfd, buffer, strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer, messageSize);
n = read(sockfd, buffer, messageSize);
if (n < 0)
error("ERROR reading from socket");
时,strncpy()
函数永远不会被调用,但代码永远不会从error()
开始。使用read()
时,一切正常。