Ad

How To Read Text File Selected By The User

- 1 answer

How can I create a file pointer and then read from an input file that the user has selected using scanf?

the input file input.txt is already in the project folder.

This is what I wrote, but I'm confused about how to read from a file based on the users input. I know that ifp = fopen("input.txt", "r"); would read the file, so my question is how can I ask the user what file needs to be read and then read the correct file using that info?

FILE *ifp;

char filename[] = {0}; 

ifp = filename;    

printf("Please enter the name of the file.\n");
scanf("%s", filename);    

ifp = fopen("filename", "r");
Ad

Answer

Remove the quotes, that makes it a string literal, you need the actual variable filename which stores the name of the file:

filename should also have sufficient size to hold the file name:

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

int main() {

    FILE *ifp;
    char filename[50]; //50 char buffer

    printf("Please enter the name of the file.\n");
    scanf("%49s", filename); //%49s limits the size to the container, -1 for null terminator

    ifp = fopen(filename, "r"); //<-- remove quotes

    //checking for file opening error
    if(ifp == NULL) {
        perror("fopen");
        return(EXIT_FAILURE);
    }
    //...
}
Ad
source: stackoverflow.com
Ad