gpt4 book ai didi

c - 在 C 中逐行浏览文本文件

转载 作者:太空狗 更新时间:2023-10-29 16:17:51 24 4
gpt4 key购买 nike

我一直在为我的 CIS 类(class)做一个小练习,我对 C 用来读取文件的方法感到非常困惑。我真正需要做的就是逐行读取文件并使用从每一行收集的信息进行一些操作。我尝试使用 getline 方法和其他方法,但没有成功。我的代码目前如下:

int main(char *argc, char* argv[]){
const char *filename = argv[0];
FILE *file = fopen(filename, "r");
char *line = NULL;

while(!feof(file)){
sscanf(line, filename, "%s");
printf("%s\n", line);
}
return 1;
}

现在我遇到了 sscanf 方法的段错误,我不确定为什么。我是一个彻头彻尾的 C 菜鸟,只是想知道我是否遗漏了一些大局。谢谢

最佳答案

如此少的行中有如此多的问题。我可能忘记了一些:

  • argv[0]是程序名,不是第一个参数;
  • 如果你想读入一个变量,你必须分配它的内存
  • 一个从不在 feof 上循环,一个在 IO 函数上循环直到它失败,然后 feof 用于确定失败的原因,
  • sscanf是用来解析一行的,如果你想解析一个文件,就用fscanf,
  • "%s"将作为 ?scanf 系列的格式在第一个空格处停止
  • 读取一行,标准函数是fgets,
  • 从 main 返回 1 意味着失败

所以

#include <stdio.h>

int main(int argc, char* argv[])
{
char const* const fileName = argv[1]; /* should check that argc > 1 */
FILE* file = fopen(fileName, "r"); /* should check the result */
char line[256];

while (fgets(line, sizeof(line), file)) {
/* note that fgets don't strip the terminating \n, checking its
presence would allow to handle lines longer that sizeof(line) */
printf("%s", line);
}
/* may check feof here to make a difference between eof and io failure -- network
timeout for instance */

fclose(file);

return 0;
}

关于c - 在 C 中逐行浏览文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9206091/

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