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

How to read line wise from a file in c (Ubuntu)?

我试图从文件中逐行提取字符串,但它没有给我 output.The 文件在标记中有一些词 wise.Here 是我的代码:

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

我在 all.The 处没有输出,程序成功执行,没有任何输出!

您的代码中有几处错误。 第一:你没有关闭文件。 第二:您使用尚未分配的 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;
}