Search code examples
cstringtextstdio

Trying to make a simple program (in C) that copies all non empty lines from a given text file into a new text file


This is what I tried doing (if the first charcacter of a line is '\n' it must necessarily be an empty line) but it gives me the error message: "Thread 1: EXC_BAD_ACCESS (code=1, address=0x68" at the line of fgets..

#include<stdio.h>
#define MAX_LEN 80

int main(int argc, char *argv[])
{
    FILE *fin,*fout;
    fin=fopen("poem_in.txt","r");
    fout=fopen("poem_out.txt","w");
    char line[MAX_LEN];

    do {
        fgets(line, MAX_LEN, fin);
        if ((line[0])!='\n') fputs(line,fout);
    } while(fgets(line, MAX_LEN, fin)!=NULL);

    fclose(fin);
    fclose(fout);
    return 0;
}

I tried looking at the correction my professor gave but she used strcmp(line,"\n") so its not very useful and I don't get how its possible to compare a string and a char? Any help at all would be greatly appreciated and would be of great help in my studies!


Solution

  • You're calling fgets() twice each time through the loop. As a result, you only check every other line for being empty.

    Do it like this instead.

    while (fgets(line, MAX_LEN, fin)) {
        if ((line[0])!='\n') fputs(line,fout);
    }
    

    If you're getting an error on the fgets() line, it's probably because the file wasn't opened successfully. You should check it first.

        fin=fopen("poem_in.txt","r");
        if (!fin) {
            fprintf(stderr, "Can't open put file poem_in.txt\n");
            exit(1);
        }
        fout=fopen("poem_out.txt","w");
        if (!fout) {
            fprintf(stderr, "Can't open output file poem_out.txt\n");
            exit(1);
        }