我想从结构体中的文件中存储信息。我的文件由行组成(每行必须是不同的结构)和列,每列都是不同的数据。文件看起来是这样的:将空格分隔的文件转换为结构数组C
1 AB
2 CD
3 CD
4 AB
我的结构是这样的(其中节点数量是第一个整数,节点类型是两个字母):
struct nodes{
int nodeNumber;
char nodeType[2];
};
到目前为止我的代码是这样的:
lines = lineCount(nodes); //calculates how many lines file has
struct nodes node[lines]; //creates structure array
no = fopen(nodes, mode);
if(no == NULL){
printf("Can't find the files.");
exit(1);
}else{
for(i = 0; i < lines; i++){
fscanf(no, "%d %2c \n", &id, current);
node[i].nodeNumber = id;
strcpy(node[i].nodeType, current);
}
}
当我调试当前值是:当前= \“AB \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \“而不只是AB
有什么想法吗?
“current”声明如何?你看到的只是字符缓冲区中有nul个字节。因为在C中没有什么可担心的,nul字节表示字符串的结尾。还要注意,'strcpy'会尝试在你的'nodeType'的末尾放置一个空字节,这会使缓冲区溢出。 –
我解决了我的问题,即使在我收录的代码中也是如此。感谢您的帮助! – Shepard