zee
zee

Reputation: 188

Directory of the file to be opened

int main()
{
    FILE *fp;
    fp=fopen("pr1.c","r");
    if(fp==NULL)
    {
        printf("can not open file");
    }
    getch();
    return 0;
}

In the above code, the file pr1.c should be in the same directory in which I am working, othwerwise it will print can not open file.
Is there any way by which I can open a file which is present anywhere in my computer?

Upvotes: 0

Views: 43

Answers (2)

herohuyongtao
herohuyongtao

Reputation: 50667

Yes, you can. Just use the full path of the file, or relative path based on current folder.

For example:

fp = fopen("c:\\MyDirectory\\TestFile1.txt", "r");
fp = fopen("/full/path/to/TestFile1.txt", "r");   // use ../ go to parent folder 

Updated: If you want user to enter the path, you can use

char path[201];
scanf("%200s",path);    // read from user
fp = fopen(path, "r");

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 59997

Yes use the full path

eg.

 fp = fopen("/etc/passwd", "r");

Or you can use relative paths!

Upvotes: 1

Related Questions