Reputation: 188
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
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
Reputation: 59997
Yes use the full path
eg.
fp = fopen("/etc/passwd", "r");
Or you can use relative paths!
Upvotes: 1