Reputation: 265
I have a text filed called fun on my desktop, but when I pass:
FILE* fp;
if((fp = fopen("/Users/<username>/Desktop/fun", "r")) == NULL)
{
printf("File didn't open\n");
exit(1);
}
fp is null. I have also tried
/home/<username>/Desktop/fun
and many variations, and I still can't seem to get the right file path.I am new to using files and C. Any help would be appreciated.
Upvotes: 2
Views: 1059
Reputation: 1
/*===exphome===([o]i)==================================================
* if SIn is not NULL then
* if SIn starts with '~'
* then expands $HOME, prepends it to the rest of SIn, and
* stores result in SOut or, if SOut==NULL, in a new
* allocated string and returns it
* else if SOut!=NULL
* then copies SIn into SOut and returns SOut
* else returns duplicated SIn
* else returns NULL
=*===================================================================*/
char *exphome(char *SOut, char *SIn)
{char *Rt= NULL;
char *envhome= NULL;
if(SIn)
if(*SIn=='~' && (envhome=getenv("HOME")))
{Rt= malloc(strlen(SIn)+strlen(envhome)+1);
strcpy(Rt, envhome); strcat(Rt, SIn+1);
if(SOut) {strcpy(SOut, Rt); free(Rt); Rt= SOut;}
}
else if(SOut) {strcpy(SOut, SIn); Rt= SOut;}
else Rt= strdup(SIn);
return Rt;
} /*exphome*/
and then
fopen(exphome(NULL, yourfile), ...)
Upvotes: 0
Reputation: 53326
fopen()
can't expand shell keywords.
Change
FILE* fp = fopen("~/Desktop/fun.txt", "r")
to
FILE* fp = fopen("/home/<yourusername>/Desktop/fun.txt", "r")
Characters like '~', '*'
are interpreted by the shell and expanded.
Upvotes: 6
Reputation: 304
Double-check that you have the correct full file path. Go to the file, right-click on it and select "properties". Are you entering in the path exactly as it is shown, including any suffixes? I.e. if the file is called "file.txt", make sure you include the ".txt" suffix in your code.
Upvotes: -1
Reputation: 3807
It looks like the answers have prompted edits of original problem. However, as it is currently written there is NO extension on the file name? Is this really true? or does the file end in "*.txt" etc.?
Upvotes: -1
Reputation: 780984
You can't use ~
in pathnames to represent the user's home directory. That notation is recognized by shells and some other applications, but it's not part of the Unix filesystem interface. You need to spell out the user's actual home directory.
fopen("/home/username/Desktop/fun.txt", "r")
Upvotes: 4
Reputation: 123498
You need to expand ~
. Use getenv("HOME")
.
getenv
at opengroup even provides some code:
const char *name = "HOME";
char *value;
value = getenv(name);
Upvotes: 3
Reputation: 206689
The ~
in the path is probably the issue. It's your shell that expands that on the command line. fopen
doesn't invoke a shell to do substitutions on the path, you'll need to do that yourself.
So pass a complete (relative or absolute) path to fopen
, not something that requires shell expansions (~
, globbing patterns or shell variables).
Upvotes: 3