0

I know how to read and write to a file, but I am including fopen() in my university project, and we are required to send everything that is required to run the program to the lecturer. But if the directory names change, is there a possibility that my program would not be able to read the file?

int main(void)
{

    FILE * fptr;

    fptr = fopen("C:\\Users\\username\\Documents\\folder\\filename.txt", "r");

    char oneline[MAX_LEN];

    while (!feof(fptr))
    {
        while (fgets(oneline, sizeof(oneline), fptr) != NULL)
            printf("%s", oneline);
    }

    fclose(fptr);

    return 0;
}

For example, if my professor downloads the file, and it is kept in downloads instead of documents like the directory I wrote, wouldn't the file be unable to be read? And if so, is there a way for me to make my code "adapt" to the changes in directory?

  • You can use relative path instead of absolute path. So if `filename.txt` is stored in folder and the source files are also in "folder" and you are sending "folder" to your lecturer, then try using `fopen("filename.txt", "r");` – kiner_shah May 25 '19 at 10:36
  • 1
    https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong – Mat May 25 '19 at 10:38
  • 1
    @kiner_shah That's an answer. I was thinking of opening the directory and using openat but that is for when the path to the directory can change while the program is running but isn't the answer here. – Dan D. May 25 '19 at 10:49

1 Answers1

0

Use relative paths.

    //if your executable and the textfile are in the same directory just use
    fptr = fopen("filename.txt", "r");
    //if e.g. your executable is in Documents use
    fptr = fopen("folder//filename.txt", "r");

by the way, use ".." to get into the parent directory.

Alternatively, if you want to change the path at runtime, store it in a c string (char array / char pointer), so you can easily replace/change it by just setting the char pointer to the string you want.

char * path = "your path here";
char * someotherpath = "other path (maybe from userinput)"
// you can easily change your the path
if(some condtion)
    path = someotherpath;
fptr = fopen(path, "r");

It should be detected automatically whether it is a absolute or relative path.

jjj
  • 575
  • 1
  • 3
  • 16