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.

Recommended Answers

All 2 Replies

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");    

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! :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.