Re: How to write to a file including full directory in C under Unix?
- From: Kenneth Brody <kenbrody@xxxxxxxxxxx>
- Date: Thu, 14 Aug 2008 15:29:41 -0500 (CDT)
Hongyu wrote:
Dear all:
I am trying to write to a file with full directory name and file name
specified (./outdir/mytestout.txt where . is the current directory)
in
C programming language and under Unix, but got errors of Failed to
open file ./outdir/mytestout.txt. Below is the code:
#include <stdio.h>
int main(void)
{
FILE *fp;
char fname[30];
char pathname[30];
strcpy(fname,"./outdir/mytestout.txt");
fp=fopen(fname, "w");
That's the long way to do it. Unless there is some reason you
copy the literal into a buffer and then use the buffer (for
example, this is a stripped down version of "real code" where
the filename isn't a literal), you could simply do:
char fname[] = "./outdir/mytestout.txt";
fp = fopen(fname,"w");
or
fp = fopen("./outdir/mytestout.txt","w");
if (fp == NULL)
{
printf("Failed to open file %s\n", fname);
Use perror() or errno to show what was the error. For example:
perror("fopen failed");
}
else
{
fprintf(fp, "This is just a test only");
}
fclose(fp);
return 0;
}
Does the directory "outdir" exist within the current directory?
Is it writable? Does "mtestout.txt" already exist in that
subdirectory, and if so, is it writable?
Again, you need to use perror() or errno to get the actual error
that occurred. Otherwise, it's just guesswork.
[...]
--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:ThisIsASpamTrap@xxxxxxxxx>
--
comp.lang.c.moderated - moderation address: clcm@xxxxxxxxxxxx -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.
.
- References:
- Prev by Date: Re: How to write to a file including full directory in C under Unix?
- Next by Date: Re: How to write to a file including full directory in C under Unix?
- Previous by thread: Re: How to write to a file including full directory in C under Unix?
- Next by thread: Re: How to write to a file including full directory in C under Unix?
- Index(es):
Relevant Pages
|