所以我有一个txt文件,我需要从中读取该文件中写入的学生人数,并且因为每个学生都在单独的行中,这意味着我需要读取该文档中的行数。所以我需要:
打印该文档中的所有行
写下该文档的行数。
所以,我这样写:
#include "stdafx.h"
#include <stdio.h>
int _tmain(int argc, _TCHAR* Argo[]){
FILE *student;
char brst[255];
student = fopen("student.txt", "r");
while(what kind of condition to put here?)
{
fgetc(brst, 255, (FILE*)student);
printf("%s\n", brst);
}
return 0;
}
好吧,我知道我可以使用相同的循环来打印和计算行数,但我找不到任何工作规则来结束循环。我尝试的每条规则都会导致无限循环。我尝试了 brst != EOF
、brst !=\0
。因此,它工作正常并打印文档的所有元素,然后开始打印文档的最后一行,没有结束。那么有什么建议吗?我需要用 C 语言做这个作业,我使用的是 VS 2012 C++
编译器。
最佳答案
OP的代码很接近,但需要使用fgets()
而不是fgetc()
,并使用fgets()
的返回值来检测何时退出,将为 NULL @Weather Vane 。还要添加行计数器。
#include <stdio.h>
int main(void) {
FILE *student = fopen("student.txt", "r");
unsigned line_count = 0;
if (student) {
char brst[255];
// fgetc(brst, 255, (FILE*)student);
while (fgets(brst, sizeof brst, student)) {
line_count++;
printf("%u %s", line_count, brst);
}
fclose(student);
}
printf("Line Count %u\n", line_count);
return 0;
}
关于c - C语言从文件中读取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40139500/