[英]How to read line wise from a file in c (Ubuntu)?
我正在尝试从文件中逐行提取字符串,但它没有输出。该文件在令牌方面有一些话。这是我的代码:
#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的fget进行了段隔离。
通过修复,现在您的代码为:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.