gpt4 book ai didi

C - 如何读取文件的所有行

转载 作者:行者123 更新时间:2023-11-30 17:30:04 25 4
gpt4 key购买 nike

我不确定如何读取文件的所有行,atm 它只读取文本文件中代码的第一行。有人可以告诉我如何让它读取所有行吗?

#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 - 如何读取文件的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25313850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com