Search code examples
cmallocfgets

C - fgets() produces gibberish


I use VS 2010 as my IDE and this code works fine until the line where fgets is called as a puts argument. It writes down the numbers in the file fine but it also prints some annoying gibberish. Maybe I am missing a \0 somewhere, dunno. Other people tried it on other compilers like mingw or gcc and it works fine.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *a, n, i;
    char str[512];
    FILE *f;
    printf("Insert array size: ");
    scanf("%d", &n);
    if(n <= 0)
    {
        printf("%d is not an allowed value!\n", n);
        return 1;
    }
    a = (int*)malloc(n * sizeof(int));
    if(a == NULL)
        return 2;
    putchar('\n');
    f = fopen("myarray.txt", "r+");
    if(f == NULL)
        return 3;
    for(i = 0; i < n; ++i)
    {
        printf("Insert %d. element of the array: ", i + 1);
        scanf("%d", &a[i]);
        fprintf(f, "%d ", a[i]);
    }
    putchar('\n');
    puts(fgets(str, 512, f));
    free(a);
    fclose(f);
    return 0;
}

Solution

  • At the point in your code where you call fgets your file pointer should be at the end of the file.

    Thus, fgets should be returning you the NULL pointer, since it hits EOF before reading any characters.

    Thus, you're passing the NULL pointer to puts.