Pedro Papel
Pedro Papel

Reputation: 63

Segmentation fault with fgets

I am doing a simple program just for opening a file and printing its contents line by line, but I get "Segmentation fault (core dumped)" while compiling with "gcc -o test pruebas.c" (my file is called pruebas.c) and then running the program in the Ubuntu Console from Windows 10, what could be the issue?

This is the code I wrote:

int main()
{
    char* line = NULL;
    FILE* file = fopen("D:/Documents/Uni/blur.lp", "r");
    while(fgets(line, sizeof(line), file))
    {
        printf("%s", line);
    }
    fclose(file);
    return(0);

(the ".lp" extension is the extension of an image format I have to develop for a homework)

Upvotes: 0

Views: 820

Answers (1)

pifor
pifor

Reputation: 7882

Here is a improved version of your program that takes into account above comments. It's also using preprocessor macros to define line size and file name:

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

#define LINE_SIZE 100
#define FILE_NAME "D:/Documents/Uni/blur.lp"

int main(int argc, char **argv)
{

    char line[LINE_SIZE] ;
    FILE *file ;

    file = fopen(FILE_NAME, "r");
    if (file == NULL)
    {
      perror("cannot access " FILE_NAME);
      return 1;
    }

    while(fgets(line, LINE_SIZE, file))
    {
        printf("%s", line);
    }

    fclose(file);
    return(0);

}

Upvotes: 1

Related Questions