Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
fscanf()在完成对行C的计数后不会读取数据_C - Fatal编程技术网

fscanf()在完成对行C的计数后不会读取数据

fscanf()在完成对行C的计数后不会读取数据,c,C,首先,由于堆栈溢出,我的C代码在使用fscanf()读取文件时遇到了问题 我可以这样读,但当我加上数行 FILE *edit = fopen("test.txt", "w"); char ch; int count = 0; do { ch = fgetc(edit); if (ch == '\n') count++; } while (ch != EOF); printf("Total number of lines %d\n", count); int id_temp

首先,由于堆栈溢出,我的C代码在使用fscanf()读取文件时遇到了问题

我可以这样读,但当我加上数行

FILE *edit = fopen("test.txt", "w");
char ch;
int count = 0;

do
{
    ch = fgetc(edit);
    if (ch == '\n') count++;
} while (ch != EOF);

printf("Total number of lines %d\n", count);

int id_temp = 0;
fscanf(edit, "%d", &id_temp);
printf("%d\n", id_temp);
fclose(edit);
system("pause");
id_temp将打印0,而不是从文件本身读取数字。在第一个场景中,它会打印Me2(正确)


感谢您抽出时间,有什么想法吗?

您没有倒带文件,因此
fscanf()
没有任何作用。它失败了;你没有检查它是否告诉你它失败了。另外,
fgetc()
返回一个
int
,而不是
char
。是的,我将fgetc()改为int,以及如何倒带文件
倒带(编辑)?值得注意的是,如果适用,您的算法也不会考虑不以换行符结尾(但以EOF结尾)的潜在最终行。如果你的文件在最后一行换行后有内容,它将被忽略,不会被计算为一行。好的,我只需在计算行数后添加“回放(编辑)”,就可以了,谢谢@Jonathan Leffler
FILE *edit = fopen("test.txt", "w");
char ch;
int count = 0;

do
{
    ch = fgetc(edit);
    if (ch == '\n') count++;
} while (ch != EOF);

printf("Total number of lines %d\n", count);

int id_temp = 0;
fscanf(edit, "%d", &id_temp);
printf("%d\n", id_temp);
fclose(edit);
system("pause");