1

I'm trying to extract string line by line from a file but its giving me no output.The file has some words in a token wise.Here is my code :

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

I'm getting no output at all.The program executes successfully without any output!

mch
  • 9,424
  • 2
  • 28
  • 42
Jack
  • 308
  • 6
  • 15
  • 1
    1) close tokens.txt before opening for reading. Otherwise data might still be buffered 2) see "Why is “while ( !feof (file) )” always wrong?" http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Ingo Leonhardt Mar 10 '17 at 13:59
  • 1
    On some systems, `(ch = fgetc(open)) != EOF` will never evaluate to false — `fgetc()` returns an `int`, not a `char`, so `ch` should be declared as an `int`. – r3mainer Mar 10 '17 at 14:15
  • 2
    1) You should be using the standard signature of `main`: `int main(void)` 2) You're reading data into `str`, a pointer to a`char` that is not initialized. 3) You never check the return value of those `fopen`s to see if they were successful. – Spikatrix Mar 10 '17 at 14:17
  • Thanks guys for the help ... Appreciate all of your answers. :) – Jack Mar 10 '17 at 16:43

1 Answers1

0

There are several errors in your code. First: you didn't close the files. Second: you did a fgets with str which has not been allocated which will segfault.

With the fixes, now your code is:

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