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

时间:2017-03-10 13:56:07

标签: c file-handling

我试图逐行从文件中提取字符串,但它没有给我输出。文件中有一些代码明智。这是我的代码:

#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);
    }
}

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

1 个答案:

答案 0 :(得分:0)

您的代码中存在多个错误。 首先:你没有关闭文件。 第二:你做了一个没有分配的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;
}