gpt4 book ai didi

c - 如何从c(Ubuntu)中的文件中逐行读取?

转载 作者:行者123 更新时间:2023-11-30 16:49:08 27 4
gpt4 key购买 nike

我试图从文件中逐行提取字符串,但它没有给我任何输出。该文件在 token 中包含一些单词。这是我的代码:

#include<stdio.h>
#include<string.h>
main(void)
{
FILE *open;
open = fopen("assembly.txt", "r");
FILE *write;
write = fopen("tokens.txt", "w");
FILE *a;

char ch;
char *str;

while ((ch = fgetc(open)) != EOF)
{
if (ch == 32 || ch == ',' || ch == '#')
fprintf(write, "\n");

else
fprintf(write, "%c", ch);
}

a = fopen("tokens.txt", "r");

while (!feof(a))
{
if (fgets(str, 126, a))
printf("%s", str);
}
}

我根本没有得到任何输出。程序执行成功,没有任何输出!

最佳答案

您的代码中有几个错误。首先:您没有关闭文件。第二:您对 str 执行了 fgets,但尚未分配,这将出现段错误。

修复后,现在您的代码是:

#include<stdio.h>
#include<string.h>
int main(void)
{
FILE *open;
open = fopen("assembly.txt", "r");
FILE *write;
write = fopen("tokens.txt", "w");
FILE *a;

char ch;
char str[127];

while ((ch = fgetc(open)) != EOF)
{
if (ch == 32 || ch == ',' || ch == '#')
fprintf(write, "\n");

else
fprintf(write, "%c", ch);
}

fclose(write);
fclose(open);
a = fopen("tokens.txt", "r");

while (!feof(a))
{
if (fgets(str, 126, a))
printf("%s", str);
}
fclose(a);
return 0;
}

关于c - 如何从c(Ubuntu)中的文件中逐行读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42720100/

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