C-如何读取文件的所有行 [英] C - How do i read all lines of a file
本文介绍了C-如何读取文件的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不确定如何读取文件的所有行,因为atm仅读取文本文件中代码的第一行.有人可以告诉我如何使它读取所有行吗?
Im unsure how to read all the lines of a file, atm it only reads the first line of the code in the text file. Can someone show me how to make it read all the lines?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
FILE *fp;
fp = fopen("specification.txt", "r");
char ** listofdetails;
listofdetails = malloc(sizeof(char*)*6);
listofdetails[0] = malloc(sizeof(char)*100);
fgets(listofdetails[0], 100, fp);
/*strcpy(listofdetails[0], "cars");*/
printf("%s \n", listofdetails[0]);
free(listofdetails[0]);
free(listofdetails);
fclose(fp);
return 0;
}
我的文本文件:
10X16 de4 dw9 ds8 g8,7 m3,4 h6,5 p2,2
10X16 de4 dw9 ds8 g8,7 m3,4 h6,5 p2,2
10X16 de4 dw9 ds8 g8,7 m3,4 h6,5 p2,2
推荐答案
#include <stdio.h>
#include <assert.h>
int main(int argc, const char * argv[])
{
FILE *file = fopen("specification.txt", "r");
char currentline[100];
assert(file != NULL);
while (fgets(currentline, sizeof(currentline), file) != NULL) {
fprintf(stderr, "got line: %s\n", currentline);
/* Do something with `currentline` */
}
fclose(file);
}
这篇关于C-如何读取文件的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文