Search code examples
cfileiocharfile-writing

Printing char to file gives weird result


So I am printing char's to a file and whenever the line ends it just does something weird.

This is the code I use:

void opdracht43() {
    FILE *file;
    FILE *file2;
    file = fopen("opdracht1.1.cpp", "r");
    file2 = fopen("Disc.c", "w");
    int p;
    char a[100];
    while (fgets(a, 100, file)) {
        for (int i = 0; i < sizeof a; i++) {
            if (a[i] == '\n' || a[i] == ' ' || a[i] == '\t') {
                printf("TRUE");
            }
            else {
                printf("FALSE");
                fputc(a[i], file2);
            }
        }
        return 0; //So it only prints the 1st line for now.
    }
    fclose(file);
    fclose(file2);
}

And when this runs this is the text it gives:

#include<stdio.h> ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ

The space between > and Ì gives me a weird black nul in notepad++

The first line of the file is:

#include<stdio.h>

I hope I can find some help here :)


Solution

  • Change

    for (int i = 0; i < sizeof a; i++) {
    

    to

    for (int i = 0; a[i] != '\0' && i < sizeof a; i++) {
    

    In your case, in the first call of fgets() gives array a these values: '#', 'i', 'n', 'c', ..., 'o', '.', 'h', '>' and a '\0'. However, the rest of a still contains garbages like Ì, because a is never initialised.

    The '\0' is just the "weird black nul" you mentioned. A '\0' is the signal of the end of a C-style string, but it does not stand for the end of a file, so it shouldn't be written to "Disc.c" using fputc()