-1

Hi I am currently trying my hand at C programming and am a bit stuck. I am trying to read in a .txt file line by line and process each line separately using fgets() but I need to ignore the newline in the file as it is affecting the output of my code. Any help would be great. Thanks in advance :)

static void Test ()
{

    int bufferLength;
    char* buffer = malloc(bufferLength);

    FILE *file = fopen("testing.txt", "r");

    while(fgets(buffer, bufferLength, file)) {
        FILE *file2 = fopen("tester.txt", "w");
        fprintf(file2, "%s", buffer);
        fclose(file2);
        FILE *file3 = fopen("tester.txt", "r");
        process(file3);
        fclose(file3);
    }

    fclose(file);
}
coderguy
  • 31
  • 3
  • I see nowhere the initialization of `bufferLength`. This implies that the `malloc` function will fail. – Pierre François Apr 28 '20 at 09:57
  • @PierreFrançois Well, it might fail, or it might not. The application is requesting a random amount of memory, so if one would add a check for `buffer == NULL`, this should "work" and read lines into a buffer of random size (not that such a behavior would be useful in any way). – Felix G Apr 28 '20 at 10:20

1 Answers1

2

Use:

 buffer[strcspn(buffer, "\n")] = 0;

inside of the while loop, right after going into the loop body.

Note, that bufferLength isn´t initialized by any value and as it is an object of automatic storage duration it will contain a garbage value. Using bufferLength this way is undefined behavior.

Initialize bufferLength to any reasonable buffer length, for example:

int bufferLength = 20;

This is what it shall look like:

static void Test ()
{

    int bufferLength = 20;
    char* buffer = malloc(bufferLength);

    FILE *file = fopen("testing.txt", "r");

    while(fgets(buffer, bufferLength, file)) {
        buffer[strcspn(buffer, "\n")] = 0;        // <-- here.
        FILE *file2 = fopen("tester.txt", "w");
        fprintf(file2, "%s", buffer);
        fclose(file2);
        FILE *file3 = fopen("tester.txt", "r");
        process(file3);
        fclose(file3);
    }

    fclose(file);
}

Side note: The function strcspn() is defined in the header of string.h. You need to #include it in order to use it.

Credit goes to @Tim Cas, from which I learned this trick here.