Search code examples
cstringfilescanf

Segmentation Fault when writing name of file via Termial


I have been looking into this for a while and cannot figure it out. I have the following code and a test.txt file with 10 data points:

int main(){
//opening file for reading ("r").
    char *filename;
    printf("Please enter file name: ");
    scanf("%s", filename);
    FILE *file = fopen(filename,"r");


//Counting total number of data points
    int ch; //store character reading
    while(!feof(file)){
      ch = fgetc(file);
      if(ch == '\n'){
        count++;
      }
    }
      fclose(file);
    printf("it is done \n");
    printf("%i", count);

If i code it with the filename directly, it works and it successfully counts the 10 data points. However, whenever I try to set it up to scan the filename, once i run it on the terminal and get the message "please enter file name", I write it in, and I always just end up getting "segmentation fault". What am i doing wrong, please help.


Solution

  • Like the other answerer said, it's a size problem, but you can also set the filename buffer to NULL:

    #include <stdio.h>
    #include <stdlib.h>
    
    void read_line_stdin(const char* message, char **buffer) {
      printf("%s", message);
      size_t len;
      int read = getline(buffer, &len, stdin)
      if (read == -1)
        printf("No line read...\n");
    }
    
    int main() {
      char *filename = NULL;
      read_line_input("Input filename > ", &filename);
      
      ...
      
      free(filename); // FREE the memory!
    }
    

    Edit:

    This answer was not generated with ChatGPT :)