我正在尝试用 C 编写一个程序,用于从文件中读取文本行,并创建节点来构建树。这些节点是结构体。为此,我尝试一次读六行。然而,每当我的程序到达 fscanf 行时,它似乎没有读取任何内容,将我的 int 设置为 EOF 并退出该函数。我尝试了很多格式组合,删除和添加空格、\n 等。我什至尝试制作一个单独的 fscanf 行来尝试读取单个字符串,即使这样似乎也没有扫描任何内容。我不知道为什么会发生这种情况。这是相关代码:
member_ptr readAndCreate(FILE * file){
member_node * temp;
temp = calloc(1, sizeof(member_node));
//char temp_char_array[50] = {0,0,0,0,0};
//char *overflow;
int isEnd;
//isEnd = fscanf(file, " %s", temp_char_array);
//isEnd =
isEnd = fscanf(file, " %[^\n] %[^\n] %d %[^\n] %[^\n] %[^\n]",
temp -> family,
temp -> personal,
&temp ->ID,
temp -> email,
temp -> boatClass,
temp -> boatName
);
//temp->ID = (int)strtol(temp_char_array, &overflow, 10);
if (isEnd == EOF){
printf("Something went wrong, please try again \n");
return NULL;
} else {
return temp;
}
}
这是主要功能
int main() {
char pathname[100];
FILE * file;
member_ptr top;
member_ptr temp;
printf("input file path\n");
scanf("%[^\n]", pathname);
file = fopen(pathname, "r");
if (file == NULL){
printf("file cannot be found, closing program...");
exit(1);
}
top = readAndCreate(file);
genTree(top, file);
printOutTree(top);
printf("Hello, World!\n");
return 0;
}
最佳答案
我发现您的扫描码有问题。指定字符串输入的 s
似乎丢失了。
尝试改变
isEnd = fscanf(file, " %[^\n] %[^\n] %d %[^\n] %[^\n] %[^\n]",
进入
isEnd = fscanf(file, " %[^\n]s %[^\n]s %d %[^\n]s %[^\n]s %[^\n]s",
您在 main()
函数中也有同样的错误。
关于c - 为什么我的 fscanf 似乎没有读取任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59070281/