Hello, I was wondering if someone could help me in this case.
I need the program to open a txt file. But the User shall inform the location where the file resides. Can be by text. Example: "C: \ documents \ test.txt".

To open files I know just the fopen.

4 Years
Discussion Span
Last Post by rubberman

It's still just fopen() regardless of where the file is located, for example

FILE* fp = fopen("c:\\documents\\test.txt","r");

In your program you will need to get the string as a character array because it comes from keyboard

char inbuf[255];
fgets(inbuf,sizeof(inbuf),stdin); // get string from keyboard
// now clear trailing '\n'
if(inbuf[strlen(inbuf)-1] == '\n')
    inbuf[strlen(inbuf)-1] = '\0';
FILE* fp = fopen(inbuf,"r");    

Edited by Ancient Dragon


Remember, for Windows, if your user uses backslashes (normal Windows format) for directory separators, then fopen will need double backslashes since the backslash is an "escape" character in C strings. Alternatively, you can convert the backslash into a forward slash (/) and the path should work on Windows as well as Linux/Unix/Mac, et al. Caveat Programmer! :-)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.