Ad
How To Read Text File Selected By The User
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
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page
Ad