计算文件中数组的长度

标签 c file-io

因此,在我的程序中保存的文件中显示如下

name name number
name name number
name name number
name name number
name name number

我需要获取该文件中的元素数量,因此在本例中它应该是 5

 FILE *pRead;

int num = 0;

 pRead = fopen("names.dat", "r");

 if ( pRead == NULL )

 printf("\nFile cannot be opened\n");

else



 while ( !feof(pRead) ) {

num++ //add one to num
printf("Num = ",num); //pint the value of num

 } //end loop

这就是我尝试过的,但它会无限循环。

最佳答案

您需要从循环中的文件中读取:

char buf[500];

 while ( !feof(pRead) ) {
    fgets(buf, 500, pRead);  // Read another line from the file
    num++ //add one to num
    printf("Num = ",num); //pint the value of num

 } //end loop

关于计算文件中数组的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19662755/

相关文章:

matlab - 在matlab中读取.yml文件

c - 我需要释放局部变量吗?

c语言作业与incr/decr运算符

c - 在C中使用fprintf时出现STATUS_ACCESS_VIOLATION(通过弹出框授予管理员权限)

c++ - 写入文件时,fprintf 与 printf 不同吗?

c++ - 在不使用任何图形库的情况下用C++创建文本编辑器[函数未声明错误]

c - 如何检测内存数据发生变化?

c - 难以理解使用链表实现图的方法

java - DataOutputStream.write(int b) 不写入

windows - 如何使 CreateFile 尽可能快