By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,321 Members | 1,875 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,321 IT Pros & Developers. It's quick & easy.

How to write to a file including full directory in C under Unix?

P: n/a
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");
if (fp == NULL)
{
printf("Failed to open file %s\n", fname);
}
else
{
fprintf(fp, "This is just a test only");
}
fclose(fp);
return 0;

}
I also try to write filename and directory with ,".\outdir
\mytestout.txt", or ,".//outdir//mytestout.txt" or ",".\\outdir\
\mytestout.txt", or even ,".///outdir///mytestout.txt" etc, and I
also
tried to specify the whole directory with the current directory .
(dot) replaced by the real directory name, but all failed. I searched
on the internet and only found one relevant that said to specify
filename with full path, but how to specify full path in C under
Unix?
Please help me.

Thanks for the help in advance.
Hongyu
Aug 11 '08 #1
Share this Question
Share on Google+
65 Replies


P: n/a
Hongyu <ho*******@yahoo.comwrites:
>I am trying to write to a file with full directory name and file name
specified (./outdir/mytestout.txt where . is the current directory)

Does the directory ./outdir already exist?
If not, you'll need to create the directory first - use mkdir();

Prepare to be teleported to comp.sys.linux.programmer

--
Chris.
Aug 11 '08 #2

P: n/a
On Aug 12, 1:51 am, Hongyu <hongyu...@yahoo.comwrote:
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:
Then you want comp.unix.programmer, not comp.lang.c (though your code
is topical)
#include <stdio.h>

int main(void)
{
FILE *fp;
char fname[30];
char pathname[30];

strcpy(fname,"./outdir/mytestout.txt");
fp=fopen(fname, "w");
if (fp == NULL)
{
printf("Failed to open file %s\n", fname);
}
else
{
fprintf(fp, "This is just a test only");
}

fclose(fp);
The fclose call should be in the else clause. fclose(NULL) is not
defined by ISO C. (not to be confused with free(NULL) which _is_
defined and does nothing)
>
return 0;

}
Aug 11 '08 #3

P: n/a
On 11 Aug 2008 at 22:51, Hongyu wrote:
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:
Guesses: does outdir exist? Are the permissions set correctly for you to
be able to write the file you want to write?

To find out without guessing...
printf("Failed to open file %s\n", fname);
....change this line to
perror("fopen");

and see what error message you get.

Aug 11 '08 #4

P: n/a
On Aug 11, 5:51*pm, Hongyu <ho*******@yahoo.comwrote:
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");
You can just use an initializer:

char fname[] = "./outdir/mytestout.txt";
* *fp=fopen(fname, "w");
* *if (fp == NULL)
* *{
* * * printf("Failed to open file %s\n", fname);
* *}
* *else
* *{
* * * fprintf(fp, "This is just a test only");
* *}

* *fclose(fp);

* *return 0;

}

I also try to write filename and directory with ,".\outdir
\mytestout.txt", or ,".//outdir//mytestout.txt" or ",".\\outdir\
\mytestout.txt", or even ,".///outdir///mytestout.txt" etc, and I
also
If your on UNIX, the path separator is '/', so I don't think the path
is the problem.
tried to specify the whole directory with the current directory .
(dot) replaced by the real directory name, but all failed. I searched
on the internet and only found one relevant that said to specify
filename with full path, but how to specify full path in C under
Unix?
Please help me.

Thanks for the help in advance.
Why don't you check the errno variable?
#include <stdio.h>
#include <errno.h>
#include <error.h>
#include <stdlib.h>

int main(void)
{
char fname[] = "./outdir/mytestout.txt";

FILE *fp = fopen(fname, "w");
if (fp == NULL)
{
error(0, errno, "could not open %s", fname);
exit(EXIT_FAILURE);
}

fprintf(fp, "This is just a test only");
fclose(fp);

return 0;
}

Sebastian
Aug 11 '08 #5

P: n/a
Hongyu <ho*******@yahoo.comwrote:
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");
if (fp == NULL)
{
printf("Failed to open file %s\n", fname);
}
There could be lots of reasons why you're not able to open that
file in write mode. Just the most likely:

a) It's rather dubious to specify a directory that's relative to
your current path since that restricts your program to be run
from within a single directtory
b) "./outdir" isn't an existing directory
c) "./outdir" isn't a directory you're allowed to change files in
d) "./outdir/mytestout.txt" is a file you're not allowed to open
in write mode.

The simplest way to find out what's really the problem is to call
perror() after fopen() failed. Its output should give you at least
a hint about what went wrong.

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Aug 11 '08 #6

P: n/a
On Aug 11, 7:13*pm, j...@toerring.de (Jens Thoms Toerring) wrote:
Hongyu <hongyu...@yahoo.comwrote:
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");
* *if (fp == NULL)
* *{
* * * printf("Failed to open file %s\n", fname);
* *}

There could be lots of reasons why you're not able to open that
file in write mode. Just the most likely:

a) It's rather dubious to specify a directory that's relative to
* *your current path since that restricts your program to be run
* *from within a single directtory
b) "./outdir" isn't an existing directory
c) "./outdir" isn't a directory you're allowed to change files in
d) "./outdir/mytestout.txt" is a file you're not allowed to open
* *in write mode.

The simplest way to find out what's really the problem is to call
perror() after fopen() failed. Its output should give you at least
a hint about what went wrong.

* * * * * * * * * * * * * * *Regards, Jens
--
* \ * Jens Thoms Toerring *___ * * *j...@toerring.de
* *\__________________________ * * *http://toerring.de- Hide quoted text -

- Show quoted text -

Dear all:

Thanks for all the suggestions. Yes, the "./outdir" isn't an existing
directory, because I want to create that directory and the filename
whenever I want to create it, because it will be used in the situation
when a user typed in the directory name, and i will append the
filename to that directory according to this format. But that was
unsuccessful, so i just tried this simple code to see whether it can
pass. I will test the code Sebastian suggested to see whether it can
pass. If not, what can i do to allow create a directory? I.e.,still
the same as to create a filename with full directory pathname.

Hongyu
Aug 11 '08 #7

P: n/a
On Aug 11, 7:25*pm, Hongyu <hongyu...@yahoo.comwrote:
On Aug 11, 7:13*pm, j...@toerring.de (Jens Thoms Toerring) wrote:


Hongyu <hongyu...@yahoo.comwrote:
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 openfile
./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");
* *if (fp == NULL)
* *{
* * * printf("Failed to open file %s\n", fname);
* *}
There could be lots of reasons why you're not able to open that
file in write mode. Just the most likely:
a) It's rather dubious to specify a directory that's relative to
* *your current path since that restricts your program to be run
* *from within a single directtory
b) "./outdir" isn't an existing directory
c) "./outdir" isn't a directory you're allowed to change files in
d) "./outdir/mytestout.txt" is a file you're not allowed to open
* *in write mode.
The simplest way to find out what's really the problem is to call
perror() after fopen() failed. Its output should give you at least
a hint about what went wrong.
* * * * * * * * * * * * * * *Regards, Jens
--
* \ * Jens Thoms Toerring *___ * * *j...@toerring.de
* *\__________________________ * * *http://toerring.de-Hide quoted text -
- Show quoted text -

Dear all:

Thanks for all the suggestions. Yes, the "./outdir" isn't an existing
directory, because I want to create that directory and the filename
whenever I want to create it, because it will be used in the situation
when a user typed in the directory name, and i will append the
filename to that directory according to this format. But that was
unsuccessful, so i just tried this simple code to see whether it can
pass. I will test the code Sebastian suggested to see whether it can
pass. If not, what can i do to allow create a directory? I.e.,still
the same as to create a filename with full directory pathname.

Hongyu- Hide quoted text -

- Show quoted text -
Hi,
I just tried Sebastian's code with adding a line to printf the errno,
and I got:

./a.out: could not open ./outdir/mytestout.txt: No such file or
directory
errno is 2

I then changed the fopen line as FILE *fp = fopen(fname, "w+");
(replaced w+ to w)

but still get the same error. What should I do? Thanks a lot.

Aug 11 '08 #8

P: n/a
>I just tried Sebastian's code with adding a line to printf the errno,
>and I got:

./a.out: could not open ./outdir/mytestout.txt: No such file or
directory
errno is 2

I then changed the fopen line as FILE *fp = fopen(fname, "w+");
(replaced w+ to w)

but still get the same error. What should I do? Thanks a lot.
Pick your approach:

1. Specify a path using an existing directory.
2. Manually create the directory first.
3. Parse the file name for parent directories, and check if they
exist, and create them if not. This likely requires functions
that are not standard C, like mkdir(), stat(), and the assumption
that '/' is a path separator.

Aug 11 '08 #9

P: n/a
Hongyu wrote:

I just tried Sebastian's code with adding a line to printf the errno,
and I got:

./a.out: could not open ./outdir/mytestout.txt: No such file or
directory
errno is 2

I then changed the fopen line as FILE *fp = fopen(fname, "w+");
(replaced w+ to w)

but still get the same error. What should I do? Thanks a lot.
You should really be posting to a UNIX newsgroup. However, if the
directory doesn't exist, you can NOT create it by opening a file in it.
No matter how much you want to.

You'll have to first create the directory. Something like:

system("mkdir outdir");

perhaps.

Brian
Aug 11 '08 #10

P: n/a
In article <18**********************************@2g2000hsn.go oglegroups.com>,
Hongyu <ho*******@yahoo.comwrote:
>Thanks for all the suggestions. Yes, the "./outdir" isn't an existing
directory, because I want to create that directory and the filename
whenever I want to create it, because it will be used in the situation
when a user typed in the directory name, and i will append the
filename to that directory according to this format.
You need to create the directory before you create the file in it.
On unix, use the mkdir() function - see the manual page for details.

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Aug 11 '08 #11

P: n/a
On Aug 11, 7:49*pm, "Default User" <defaultuse...@yahoo.comwrote:
Hongyu wrote:
I just tried Sebastian's code with adding a line to printf the errno,
and I got:
./a.out: could not open ./outdir/mytestout.txt: No such file or
directory
errno is 2
I then changed the fopen line as *FILE *fp = fopen(fname, "w+");
(replaced w+ to w)
but still get the same error. What should I do? Thanks a lot.

You should really be posting to a UNIX newsgroup. However, if the
directory doesn't exist, you can NOT create it by opening a file in it.
No matter how much you want to.

You'll have to first create the directory. Something like:

system("mkdir outdir");

perhaps.

Brian
Thanks. I will try that.
Aug 12 '08 #12

P: n/a
On Aug 11, 7:54*pm, rich...@cogsci.ed.ac.uk (Richard Tobin) wrote:
In article <18a29ac5-cd6f-4da9-8ae0-73e7127db...@2g2000hsn.googlegroups.com>,

Hongyu *<hongyu...@yahoo.comwrote:
Thanks for all the suggestions. Yes, the "./outdir" isn't an existing
directory, because I want to create that directory and the filename
whenever I want to create it, because it will be used in the situation
when a user typed in the directory name, and i will append the
filename to that directory according to this format.

You need to create the directory before you create the file in it.
On unix, use the mkdir() function - see the manual page for details.

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Thanks. I know how to create directory in Unix using mkdir, but what i
don't know is how to make it in the C programming. I will try Brian's
method which mentioned using system method to achieve it. I guess it
will work.
Aug 12 '08 #13

P: n/a
Hongyu wrote, On 11/08/08 23:51:
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 <errno.h>

<snip>
strcpy(fname,"./outdir/mytestout.txt");
errno = 0; /* C library functions don't clear errno */
fp=fopen(fname, "w");
if (fp == NULL)
{
if (errno)
perror("The C library reported");

The C standard does not guarantee that errno will be set up fopen, but
it does allow it and many implementations will set it to a useful value.
printf("Failed to open file %s\n", fname);
}
else
{
fprintf(fp, "This is just a test only");
}
fclose(fp);
Here you try and close the file even if you did not succeed in opening
it. This is a *bad* thing to try and could make your program go
***BANG!!!***
return 0;

}
I also try to write filename and directory with ,".\outdir
\mytestout.txt", or ,".//outdir//mytestout.txt" or ",".\\outdir\
\mytestout.txt", or even ,".///outdir///mytestout.txt" etc, and I
also
All of the above are likely to be wrong as you are using Unix.
tried to specify the whole directory with the current directory .
(dot) replaced by the real directory name, but all failed. I searched
on the internet and only found one relevant that said to specify
filename with full path, but how to specify full path in C under
Unix?
comp.unix.programmer would be the place to ask about Unix problems, but
I suspect if you try my C suggestion above you will stand a better
chance of finding the problem.

Oh, and you should probably check the directory exists (including
correct case) and for correct permissions on directories and files, but
that is all Unix specific so ask about it on comp.unix.programmer.
--
Flash Gordon
Aug 12 '08 #14

P: n/a
On Aug 11, 7:22*pm, Flash Gordon <s...@flash-gordon.me.ukwrote:
Hongyu wrote, On 11/08/08 23:51:
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 <errno.h>

<snip>
* *strcpy(fname,"./outdir/mytestout.txt");

* * * errno = 0; /* C library functions don't clear errno */
* *fp=fopen(fname, "w");
* *if (fp == NULL)
* *{

* * * * *if (errno)
* * * * * * perror("The C library reported");

The C standard does not guarantee that errno will be set up fopen, but
it does allow it and many implementations will set it to a useful value.
* * * printf("Failed to open file %s\n", fname);
* *}
* *else
* *{
* * * fprintf(fp, "This is just a test only");
* *}
* *fclose(fp);

Here you try and close the file even if you did not succeed in opening
it. This is a *bad* thing to try and could make your program go
***BANG!!!***
* *return 0;
}
I also try to write filename and directory with ,".\outdir
\mytestout.txt", or ,".//outdir//mytestout.txt" or ",".\\outdir\
\mytestout.txt", or even ,".///outdir///mytestout.txt" etc, and I
also

All of the above are likely to be wrong as you are using Unix.
tried to specify the whole directory with the current directory .
(dot) replaced by the real directory name, but all failed. I searched
on the internet and only found one relevant that said to specify
filename with full path, but how to specify full path in C under
Unix?

comp.unix.programmer would be the place to ask about Unix problems, but
I suspect if you try my C suggestion above you will stand a better
chance of finding the problem.

Oh, and you should probably check the directory exists (including
correct case) and for correct permissions on directories and files, but
that is all Unix specific so ask about it on comp.unix.programmer.
--
Flash Gordon
Thanks for the comments, Flash. I do learn a lot from all the replies
on my post. I can see I have a lot to improve even just from this very
short program. But considering that i am a newbie, so it is
reasonable. Yes, you are right, the following question is to check the
status of the directory before i create it. I will ask it in the
comp.unix.programmer and hope they know how to do that in C.
Aug 12 '08 #15

P: n/a
Hongyu wrote:
>
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");
Look into permissions. On principal, use blanks around '='.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

Aug 12 '08 #16

P: n/a
On Aug 11, 7:49*pm, "Default User" <defaultuse...@yahoo.comwrote:
Hongyu wrote:
I just tried Sebastian's code with adding a line to printf the errno,
and I got:
./a.out: could not open ./outdir/mytestout.txt: No such file or
directory
errno is 2
I then changed the fopen line as *FILE *fp = fopen(fname, "w+");
(replaced w+ to w)
but still get the same error. What should I do? Thanks a lot.

You should really be posting to a UNIX newsgroup. However, if the
directory doesn't exist, you can NOT create it by opening a file in it.
No matter how much you want to.

You'll have to first create the directory. Something like:

system("mkdir outdir");

perhaps.

Brian
Just like to let you, the people here and the other people who have
similar problems know that your method worked. i.e., a directory must
be created first. But now i have questions on how to check the status
of the directory in C programming under Unix. i.e. whether it is exist
or not, whether it is with writting permission. I am asking this in
comp.unix.programmer now.
Aug 12 '08 #17

P: n/a
On Aug 11, 7:30*pm, CBFalconer <cbfalco...@yahoo.comwrote:
Hongyu wrote:
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");

Look into permissions. *On principal, use blanks around '='.

--
*[mail]: Chuck F (cbfalconer at maineline dot net)
*[page]: <http://cbfalconer.home.att.net>
* * * * * * Try the download section.- Hide quoted text -

- Show quoted text -

Can you explain a little bit more on this? I am not sure how to use
blanks around "=" for this? Thanks.
Aug 12 '08 #18

P: n/a

Hongyu <ho*******@yahoo.comwrote in message
news:38**********************************@f36g2000 hsa.googlegroups.com...
On Aug 11, 7:22 pm, Flash Gordon <s...@flash-gordon.me.ukwrote:
tried to specify the whole directory with the current directory .
(dot) replaced by the real directory name, but all failed. I searched
on the internet and only found one relevant that said to specify
filename with full path, but how to specify full path in C under
Unix?
comp.unix.programmer would be the place to ask about Unix problems, but
I suspect if you try my C suggestion above you will stand a better
chance of finding the problem.

Oh, and you should probably check the directory exists (including
correct case) and for correct permissions on directories and files, but
that is all Unix specific so ask about it on comp.unix.programmer.
Thanks for the comments, Flash. I do learn a lot from all the replies
on my post. I can see I have a lot to improve even just from this very
short program. But considering that i am a newbie, so it is
reasonable. Yes, you are right, the following question is to check the
status of the directory before i create it. I will ask it in the
comp.unix.programmer and hope they know how to do that in C.
You've been trolled by some of the masters of the art here.

What you're really looking for is something called "POSIX",
which was initially developed based on Unix, but could potentially
apply to any computer system, and as a matter of fact is
included in the "C" compilers for many different types of
systems.

If you want to find out if you can open a file, try the POSIX
"C" function access(). Check the documentation for your "C"
compiler for this function, as well mkdir() and and stat()/fstat()
and some other related "POSIX" functions.

For example, to check the basic access to a file for certain
compilers for Windows systems:

/* checks if a specific file exists */
unsigned file_exists(char *file_path) {

#ifdef __WIN32__
if(access(file_path,00)!=SUCCESS)
return FALSE;

/* other system ifdef's elided, including a "Unix" access() */
....
/* if all else fails, this is the C "standard" way of doing it */
#else
FILE *file;

if((file=fopen(file_path,"r"))==NULL)
return FALSE;

fclose(file);
#endif

return TRUE;
}

Note that the C "standard" doesn't recognize the concept of
directories, which is the excuse the trolls will use for their trollery.
However, in most cases you can do any of this stuff using "C",
either through system-specific functions, or "open" POSIX-style
functions.

As far as your specific problem is concerned, it is generally dead-easy
to open a file in a running program in a UNIX filesystem if you have
permissions,
there is nothing very "tricky" about how you specify a path in UNIX (or
"POSIX"; access() will reveal if permissions are the problem, or something
else, via errno. As has been noted, you may have to recursively create
directories if they don't actually exist; I have previously posted code to
do this, but was trolled mercilessly for the information so you're on
your own from here on out...

---
William Ernest Reid
Aug 12 '08 #19

P: n/a
Hongyu <ho*******@yahoo.comwrites:
On Aug 11, 7:30*pm, CBFalconer <cbfalco...@yahoo.comwrote:
>Hongyu wrote:
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");

Look into permissions. *On principal, use blanks around '='.

Can you explain a little bit more on this? I am not sure how to use
blanks around "=" for this? Thanks.
Chuck was merely making a suggestion about the layout of your code,
something that will make it easier to read but will have no effect on
its behavior. You should also add a space after each comma.

Rather than this:

strcpy(fname,"./outdir/mytestout.txt");
fp=fopen(fname, "w");

write this:

strcpy(fname, "./outdir/mytestout.txt");
fp = fopen(fname, "w");

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 12 '08 #20

P: n/a
"Default User" <de***********@yahoo.comwrites:
Hongyu wrote:
>I just tried Sebastian's code with adding a line to printf the errno,
and I got:

./a.out: could not open ./outdir/mytestout.txt: No such file or
directory
errno is 2

I then changed the fopen line as FILE *fp = fopen(fname, "w+");
(replaced w+ to w)

but still get the same error. What should I do? Thanks a lot.

You should really be posting to a UNIX newsgroup. However, if the
directory doesn't exist, you can NOT create it by opening a file in it.
No matter how much you want to.
How do you know that? A conforming C implementation could easily
create any necessary directories as a side effect of creating a file.

You're giving him Unix advice, not C advice. (Your Unix advice
happens to be correct.)
You'll have to first create the directory. Something like:

system("mkdir outdir");

perhaps.
Something like that, yes. But if the above system() call actually
works, then there will very likely be a better, but (equally)
non-portable, way to do the same thing.

<OT>
If system("mkdir outdir") works, then you can replace it with
mkdir("outdir", blah), where "blah" is the second argument to the
mkdir function.

The only good reason I can think of to use system() here is if you
need to check *at run time* whether mkdir is supported on the current
system.
</OT>

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 12 '08 #21

P: n/a
On Aug 11, 8:49*pm, Keith Thompson <ks***@mib.orgwrote:
"Default User" <de***********@yahoo.comwrites:
Hongyu wrote:
I just tried Sebastian's code with adding a line to printf the errno,
and I got:
./a.out: could not open ./outdir/mytestout.txt: No such file or
directory
errno is 2
I then changed the fopen line as *FILE *fp = fopen(fname, "w+");
(replaced w+ to w)
but still get the same error. What should I do? Thanks a lot.
You should really be posting to a UNIX newsgroup. However, if the
directory doesn't exist, you can NOT create it by opening a file in it.
No matter how much you want to.

How do you know that? *A conforming C implementation could easily
create any necessary directories as a side effect of creating a file.
How?

<snip>

Sebastian

Aug 12 '08 #22

P: n/a
Hongyu wrote:
CBFalconer <cbfalco...@yahoo.comwrote:
>Hongyu wrote:
>>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");

Look into permissions. On principal, use blanks around '='.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.- Hide quoted text -

- Show quoted text -
------------------ snip from "-- " to here. ---------------
>
Can you explain a little bit more on this? I am not sure how to use
blanks around "=" for this? Thanks.
Don't quote sigs. You should have stripped the marked portion
after the "-- " marker.

That suggestion was separate. It meant write "fp = fopen(...)" in
place of "fp=fopen(...)". It makes your code more readable, and
avoids many confusing errors in compilation.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
Aug 12 '08 #23

P: n/a
Hongyu said:

<snip>
Yes, you are right, the following question is to check the
status of the directory before i create it. I will ask it in the
comp.unix.programmer and hope they know how to do that in C.
They will know. In any case, even if they didn't, the way POSIX works, you
would have little difficulty in translating a reply written in any
sensible mainstream language.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Aug 12 '08 #24

P: n/a
s0****@gmail.com writes:
On Aug 11, 8:49*pm, Keith Thompson <ks***@mib.orgwrote:
>"Default User" <de***********@yahoo.comwrites:
Hongyu wrote:
I just tried Sebastian's code with adding a line to printf the errno,
and I got:
>./a.out: could not open ./outdir/mytestout.txt: No such file or
directory
errno is 2
>I then changed the fopen line as *FILE *fp = fopen(fname, "w+");
(replaced w+ to w)
>but still get the same error. What should I do? Thanks a lot.
You should really be posting to a UNIX newsgroup. However, if the
directory doesn't exist, you can NOT create it by opening a file in it.
No matter how much you want to.

How do you know that? *A conforming C implementation could easily
create any necessary directories as a side effect of creating a file.

How?
In some system-specific manner.

Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w") could
implicitly invoke the equivalent of "mkdir -p /foo/bar" before
actually creating the file.

That's just one example. The point is that the C standard doesn't
mention directories at all. There's nothing in the standard that says
an implementation *can't* create a directory as a side effect of
creating a file.

(I'm not aware of any actual implementation that does this.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 12 '08 #25

P: n/a
On 11 Aug 2008 at 23:57, Hongyu wrote:
Thanks. I know how to create directory in Unix using mkdir, but what i
don't know is how to make it in the C programming. I will try Brian's
method which mentioned using system method to achieve it. I guess it
will work.
It will "work", but it is a stupid solution. "Brian" is a troll who
wants to disrupt the group with endless topicality and netnanny flame
wars, and in this case he has led you down the wrong path. Running
programs using system() can be a security issue, and you get no way of
discovering errors that may occur.

Instead, use the portable POSIX solution:

#include <sys/stat.h>
#include <sys/types.h>

then do something like

if(mkdir("my_new_directory", S_IRWXU | S_IRWXG | S_IRWXO) == -1) {
/* an error occurred - check errno to find out what */
} else {
/* success - carry on */
}

Aug 12 '08 #26

P: n/a
In article <c3**********************************@c65g2000hsa. googlegroups.com>,
Hongyu <ho*******@yahoo.comwrote:
>You need to create the directory before you create the file in it.
On unix, use the mkdir() function - see the manual page for details.
>Thanks. I know how to create directory in Unix using mkdir, but what i
don't know is how to make it in the C programming.
I didn't say use the mkdir command, I said use the mkdir() function.

Depending on which version of unix you use, something like "man 2 mkdir"
will show you the manual page.

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Aug 12 '08 #27

P: n/a
On 11 Aug 2008 at 23:30, CBFalconer wrote:
On principal, use blanks around '='.
Look, other people have different coding styles and conventions to you.
Many of them post code to Usenet. Just live with it, instead of always
prissily trying to impose "the CBF house style" (with is awful, btw) on
the rest of the world.

And learn how to spell principle. Who's going to take style advice from
an illiterate?

Aug 12 '08 #28

P: n/a
In article <69*********************@bgtnsc04-news.ops.worldnet.att.net>,
Bill Reid <ho********@happyhealthy.netwrote:
>What you're really looking for is something called "POSIX",
which was initially developed based on Unix, but could potentially
apply to any computer system, and as a matter of fact is
included in the "C" compilers for many different types of
systems.
POSIX is included in the C compilers for "many different types of
systems"?? Would I be likely to recognize the names of any of
those systems??

POSIX is the "Portable Operating System Interface". A C compiler
does not implement operating system interfaces: to do so would
take them out of the realm of being *operating system* interfaces
into the realm of being *application* entities.

Sometimes C compilers bundle in, as extensions, header files useful
with POSIX -- but the operating system behaviours are left to
the operating system to implement, not delivered by the C compiler.
Are you aware of the following, Bill?

http://support.microsoft.com/kb/308259

POSIX and OS/2 are not supported in Windows XP or in Windows Server 2003

INTRODUCTION
There is no support for POSIX or OS/2 programs in Microsoft Windows
XP-based or in Microsoft Windows Server 2003-based operating
systems.

http://www.microsoft.com/downloads/d...displaylang=en

Overview
Utilities and SDK for UNIX-Based Applications is an add-on to the
Subsystem for UNIX-Based Applications (referred to as SUA, hence
forth) component that shipped in Microsoft Windows Vista /
Windows Server 2008 RTM. [...]

System Requirements

* Supported Operating Systems: Windows Server 2008; Windows
Vista Enterprise; Windows Vista Enterprise 64-bit edition;
Windows Vista Service Pack 1; Windows Vista Ultimate; Windows
Vista Ultimate 64-bit edition
If it was just a matter of having the right C compiler, then why
the restrictions on the supported editions? Why no support for
Vista Starter, Vista Home, Vista Home Premium, or Vista Business ?
--
"To the modern spirt nothing is, or can be rightly known,
except relatively and under conditions." -- Walter Pater
Aug 12 '08 #29

P: n/a
On 12 Aug, 08:47, Antoninus Twink <nos...@nospam.invalidwrote:
On 11 Aug 2008 at 23:57, Hongyu wrote:
Thanks. I know how to create directory in Unix using mkdir, but what i
don't know is how to make it in the C programming. I will try Brian's
method which mentioned using system method to achieve it. I guess it
will work.

It will "work", but it is a stupid solution.
this is probably so, under Posix. On another OS it may be the only
way.

"Brian" is a troll who
wants to disrupt the group with endless topicality and netnanny flame
wars,
"Twink" is a troll who wants to disrupt the group by massive off-topic
postings.
and in this case he has led you down the wrong path. Running
programs using system() can be a security issue,
I doubt it is a security issue with mkdir. But this is off-topic
on comp.lang.c anyway.

and you get no way of
discovering errors that may occur.

Instead, use the portable POSIX solution:
but not necessarily portable to non-Posix systems.

#include <sys/stat.h>
#include <sys/types.h>

then do something like

if(mkdir("my_new_directory", S_IRWXU | S_IRWXG | S_IRWXO) == -1) {
* /* an error occurred - check errno to find out what */} else {

* /* success - carry on */
<snip>
--
Nick Keighley
Aug 12 '08 #30

P: n/a
In article <29**********************************@l64g2000hse. googlegroups.com>,
Nick Keighley <ni******************@hotmail.comwrote:
Thanks. I know how to create directory in Unix using mkdir, but what i
don't know is how to make it in the C programming. I will try Brian's
method which mentioned using system method to achieve it. I guess it
will work.
>It will "work", but it is a stupid solution.
>this is probably so, under Posix. On another OS it may be the only
way.
Very unlikely - do you know of any operating system where that is
true?. And the system() version is just as unportable as the mkdir()
version, because you have to know what the operating system's command
for creating directories is. If you can find that out, you can find
out what the function is.

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Aug 12 '08 #31

P: n/a
Richard Tobin wrote:
In article
<29**********************************@l64g2000hse. googlegroups.com>,
Nick Keighley <ni******************@hotmail.comwrote:
>Thanks. I know how to create directory in Unix using mkdir, but
what i don't know is how to make it in the C programming. I will
try Brian's method which mentioned using system method to achieve
it. I guess it will work.
>>It will "work", but it is a stupid solution.
>>this is probably so, under Posix. On another OS it may be the only
way.

Very unlikely - do you know of any operating system where that is
true?. And the system() version is just as unportable as the mkdir()
version, because you have to know what the operating system's command
for creating directories is. If you can find that out, you can find
out what the function is.
Well, with interactive programs, one *could* query the user for the
system's directory creation command, while a function is hard-coded...

Aug 12 '08 #32

P: n/a
In article <g7***********@pc-news.cogsci.ed.ac.ukri*****@cogsci.ed.ac.uk (Richard Tobin) writes:
In article <29**********************************@l64g2000hse. googlegroups.com>,
....
Thanks. I know how to create directory in Unix using mkdir, but what i
don't know is how to make it in the C programming. I will try Brian's
method which mentioned using system method to achieve it. I guess it
will work.
....
this is probably so, under Posix. On another OS it may be the only
way.

Very unlikely - do you know of any operating system where that is
true?
Original System V Unix.
And the system() version is just as unportable as the mkdir()
version, because you have to know what the operating system's command
for creating directories is. If you can find that out, you can find
out what the function is.
But in System V Unix the function to create a directory is not sufficient.
You need also the functions to create links to the parent directory en
to the directory itself. And only "root" is allowed to do that.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Aug 12 '08 #33

P: n/a
On Aug 12, 3:42*am, Keith Thompson <ks...@mib.orgwrote:
s0s...@gmail.com writes:
On Aug 11, 8:49*pm, Keith Thompson <ks...@mib.orgwrote:
"Default User" <defaultuse...@yahoo.comwrites:
Hongyu wrote:
I just tried Sebastian's code with adding a line to printf the errno,
and I got:
./a.out: could not open ./outdir/mytestout.txt: No such file or
directory
errno is 2
I then changed the fopen line as *FILE *fp = fopen(fname, "w+");
(replaced w+ to w)
but still get the same error. What should I do? Thanks a lot.
You should really be posting to a UNIX newsgroup. However, if the
directory doesn't exist, you can NOT create it by opening a file in it.
No matter how much you want to.
How do you know that? *A conforming C implementation could easily
create any necessary directories as a side effect of creating a file.
How?

In some system-specific manner.

Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w") could
implicitly invoke the equivalent of "mkdir -p /foo/bar" before
actually creating the file.

That's just one example. *The point is that the C standard doesn't
mention directories at all. *There's nothing in the standard that says
an implementation *can't* create a directory as a side effect of
creating a file.

(I'm not aware of any actual implementation that does this.)

--
Keith Thompson (The_Other_Keith) ks...@mib.org *<http://www.ghoti.net/~kst>
Nokia
"We must do something. *This is something. *Therefore, we must do this."
* * -- Antony Jay and Jonathan Lynn, "Yes Minister"- Hide quoted text-

- Show quoted text -
>Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w") could
implicitly invoke the equivalent of "mkdir -p /foo/bar" before
actually creating the file.
Thanks everyone's help. The discussion really helps, not only just on
my specific question, but also on the good coding styles etc. I think
what you mentioned here is what I tried in the beginning, but
unfortunately it didn't work, unless i create the directory first. I
am als in a Unix-like system (Linux). I think as people suggested
here, "POSIX" functions are way to go. I will study it more and try
it, and let people know the result after the testing.
Aug 12 '08 #34

P: n/a
In article <K5********@cwi.nl>, Dik T. Winter <Di********@cwi.nlwrote:
Very unlikely - do you know of any operating system where that is
true?
>Original System V Unix.
Ok, let's say "any current operating system".

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Aug 12 '08 #35

P: n/a
On Aug 12, 9:43*am, Hongyu <hongyu...@yahoo.comwrote:
On Aug 12, 3:42*am, Keith Thompson <ks...@mib.orgwrote:


s0s...@gmail.com writes:
On Aug 11, 8:49*pm, Keith Thompson <ks...@mib.orgwrote:
>"Default User" <defaultuse...@yahoo.comwrites:
Hongyu wrote:
>I just tried Sebastian's code with adding a line to printf the errno,
>and I got:
>./a.out: could not open ./outdir/mytestout.txt: No such file or
>directory
>errno is 2
>I then changed the fopen line as *FILE *fp = fopen(fname, "w+");
>(replaced w+ to w)
>but still get the same error. What should I do? Thanks a lot.
You should really be posting to a UNIX newsgroup. However, if the
directory doesn't exist, you can NOT create it by opening a file in it.
No matter how much you want to.
>How do you know that? *A conforming C implementation could easily
>create any necessary directories as a side effect of creating a file..
How?
In some system-specific manner.
Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w") could
implicitly invoke the equivalent of "mkdir -p /foo/bar" before
actually creating the file.
That's just one example. *The point is that the C standard doesn't
mention directories at all. *There's nothing in the standard that says
an implementation *can't* create a directory as a side effect of
creating a file.
(I'm not aware of any actual implementation that does this.)
--
Keith Thompson (The_Other_Keith) ks...@mib.org *<http://www.ghoti.net/~kst>
Nokia
"We must do something. *This is something. *Therefore, we must do this."
* * -- Antony Jay and Jonathan Lynn, "Yes Minister"- Hide quoted text -
- Show quoted text -
Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w") could
implicitly invoke the equivalent of "mkdir -p /foo/bar" before
actually creating the file.

Thanks everyone's help. The discussion really helps, not only just on
my specific question, but also on the good coding styles etc. I think
what you mentioned here is what I tried in the beginning, but
unfortunately it didn't work, unless i create the directory first. I
am als in a Unix-like system (Linux). I think as people suggested
here, "POSIX" functions are way to go. I will study it more and try
it, and let people know the result after the testing.- Hide quoted text -

- Show quoted text -
The discussion is really helpful and interesting. Thanks everyone's
help again. For some unknown reasons, my questioning post was not
appeared in the unix.programmer group discussion board. But from the
suggestions here, I got the code to work. Just to let people with
similar questions know how to solve the problem, here is the code I
used and POISX is the way to go. It should be mentioned that multi-
level subdirectories can only be created in the code recursively or
the parent directory is exist and writtable first (i didn't do
recursive coding in the code here).

#include <stdio.h>
#include <errno.h>
#include <error.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

int main(void)
{
char fname[40] = "mytestout.txt"; //filename
//char fpath[40] = "./testdir1/testdir2"; // filepath, doesn't work
unless testdir1 is exist and writable
char fpath[40] = "./testdir1"; // filepath, worked!
//char fpath[40] = "."; //filepath. curent directory. worked!
char wholename[100]; //filename with full path
int last;

last = (int)strlen(fpath)-1; // last char of path

//make sure the path is ended with '/'
if ((last >= 0) && (fpath[last] != '/'))
{
last++;
fpath[last] = '/'; // append '\' at the last of path
fpath[last+1] = '\0'; // terminate the path char string
}

strcpy(wholename, fpath);

strcat(wholename, fname);

// create the directory if it is not exist
if(access(fpath, F_OK) != 0) // directory nonexist
{ // actually I don't need to check this
// because the man mkdir says 'create a
directory
// if it is non-exist'. But to make
sure, keep it here

// create the directory with read/write/search permissions for
owner and group,
// and with read/search permissions for others
if(mkdir(fpath,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
{
printf("Failed to create directory %s\n", fpath);
return EXIT_FAILURE;
}
}

// write to file whose name is spcified with full path
FILE *fp = fopen(wholename, "w");
if (fp == NULL)
{
error(0, errno, "could not open %s", fname);
exit(EXIT_FAILURE);
}
else
{
fprintf(fp, "This is just a test!");
fclose(fp);
}

return EXIT_SUCCESS;

}

Aug 12 '08 #36

P: n/a
On Aug 12, 4:38*pm, Hongyu <hongyu...@yahoo.comwrote:
On Aug 12, 9:43*am, Hongyu <hongyu...@yahoo.comwrote:


On Aug 12, 3:42*am, Keith Thompson <ks...@mib.orgwrote:
s0s...@gmail.com writes:
On Aug 11, 8:49*pm, Keith Thompson <ks...@mib.orgwrote:
"Default User" <defaultuse...@yahoo.comwrites:
Hongyu wrote:
I just tried Sebastian's code with adding a line to printf the errno,
and I got:
./a.out: could not open ./outdir/mytestout.txt: No such file or
directory
errno is 2
I then changed the fopen line as *FILE *fp = fopen(fname, "w+");
(replaced w+ to w)
but still get the same error. What should I do? Thanks a lot.
You should really be posting to a UNIX newsgroup. However, if the
directory doesn't exist, you can NOT create it by opening a filein it.
No matter how much you want to.
How do you know that? *A conforming C implementation could easily
create any necessary directories as a side effect of creating a file.
How?
In some system-specific manner.
Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w") could
implicitly invoke the equivalent of "mkdir -p /foo/bar" before
actually creating the file.
That's just one example. *The point is that the C standard doesn't
mention directories at all. *There's nothing in the standard that says
an implementation *can't* create a directory as a side effect of
creating a file.
(I'm not aware of any actual implementation that does this.)
--
Keith Thompson (The_Other_Keith) ks...@mib.org *<http://www.ghoti.net/~kst>
Nokia
"We must do something. *This is something. *Therefore, we must dothis."
* * -- Antony Jay and Jonathan Lynn, "Yes Minister"- Hide quoted text -
- Show quoted text -
>Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w") could
>implicitly invoke the equivalent of "mkdir -p /foo/bar" before
>actually creating the file.
Thanks everyone's help. The discussion really helps, not only just on
my specific question, but also on the good coding styles etc. I think
what you mentioned here is what I tried in the beginning, but
unfortunately it didn't work, unless i create the directory first. I
am als in a Unix-like system (Linux). I think as people suggested
here, "POSIX" functions are way to go. I will study it more and try
it, and let people know the result after the testing.- Hide quoted text-
- Show quoted text -

The discussion is really helpful and interesting. Thanks everyone's
help again. For some unknown reasons, my questioning post was not
appeared in the unix.programmer group discussion board. But from the
suggestions here, I got the code to work. Just to let people with
similar questions know how to solve the problem, here is the code I
used and POISX is the way to go. *It should be mentioned that multi-
level subdirectories can only be created in the code recursively or
the parent directory is exist and writtable first (i didn't do
recursive coding in the code here).

#include <stdio.h>
#include <errno.h>
#include <error.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

int main(void)
{
* *char fname[40] = "mytestout.txt"; *//filename
* *//char fpath[40] = "./testdir1/testdir2"; // filepath, doesn't work
unless testdir1 is exist and writable
* *char fpath[40] = "./testdir1"; // filepath, worked!
* *//char fpath[40] = "."; *//filepath. curent directory. worked!
* *char wholename[100]; //filename with full path
* *int last;

* *last = (int)strlen(fpath)-1; // last char of path

* *//make sure the path is ended with '/'
* *if ((last >= 0) && (fpath[last] != '/'))
* *{
* * * last++;
* * * fpath[last] = '/'; // append '\' at the last of path
* * * fpath[last+1] = '\0'; // terminate the path char string
* *}

* *strcpy(wholename, fpath);

* *strcat(wholename, fname);

* *// create the directory if it is not exist
* *if(access(fpath, F_OK) != 0) // directory nonexist
* *{ * * * * * * * * * * * * * *// actually I don't need to check this
* * * * * * * * * * * * * * * *// becausethe man mkdir says 'create a
directory
* * * * * * * * * * * * * * * *// if it is non-exist'. But to make
sure, keep it here

* * * // create the directory with read/write/search permissions for
owner and group,
* * * // and with read/search permissions for others
* * * if(mkdir(fpath,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
* * * {
* * * * printf("Failed to create directory %s\n", fpath);
* * * * return EXIT_FAILURE;
* * * }
* *}

* *// write to file whose name is spcified with full path
* *FILE *fp = fopen(wholename, "w");
* * if (fp == NULL)
* *{
* * * error(0, errno, "could not open %s", fname);
* * * exit(EXIT_FAILURE);
* *}
* *else
* *{
* * * fprintf(fp, "This is just a test!");
* * * fclose(fp);
* *}

* *return EXIT_SUCCESS;

}- Hide quoted text -

- Show quoted text -- Hide quoted text -

- Show quoted text -
Sorry, the code didn't appear 100% right after the posting since the
comment lines get adjusted. Here is after the re-adjusting to make it
right:

#include <stdio.h>
#include <errno.h>
#include <error.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main(void)
{
char fname[40] = "mytestout.txt"; //filename
//char fpath[40] = "./testdir1/testdir2"; // filepath, doesn't work
unless testdir1 is exist and writable
char fpath[40] = "./testdir1"; // filepath, worked!
//char fpath[40] = "."; //filepath. curent directory. worked!
char wholename[100]; //filename with full path
int last;
last = (int)strlen(fpath)-1; // last char of path
//make sure the path is ended with '/'
if ((last >= 0) && (fpath[last] != '/'))
{
last++;
fpath[last] = '/'; // append '\' at the last of path
fpath[last+1] = '\0'; // terminate the path char string
}
strcpy(wholename, fpath);
strcat(wholename, fname);
// create the directory if it is not exist
if(access(fpath, F_OK) != 0) // directory nonexist
{ // actually I don't need to check
this
// because the man mkdir says 'create a
directory
// if it is non-exist'. But to make
sure, keep it here
// create the directory with read/write/search permissions for
owner and group,
// and with read/search permissions for others
if(mkdir(fpath,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
{
printf("Failed to create directory %s\n", fpath);
return EXIT_FAILURE;
}
}
// write to file whose name is spcified with full path
FILE *fp = fopen(wholename, "w");
if (fp == NULL)
{
error(0, errno, "could not open %s", fname);
exit(EXIT_FAILURE);
}
else
{
fprintf(fp, "This is just a test!");
fclose(fp);
}
return EXIT_SUCCESS;

}
Aug 12 '08 #37

P: n/a
On Aug 12, 4:46*pm, Hongyu <hongyu...@yahoo.comwrote:
On Aug 12, 4:38*pm, Hongyu <hongyu...@yahoo.comwrote:


On Aug 12, 9:43*am, Hongyu <hongyu...@yahoo.comwrote:
On Aug 12, 3:42*am, Keith Thompson <ks...@mib.orgwrote:
s0s...@gmail.com writes:
On Aug 11, 8:49*pm, Keith Thompson <ks...@mib.orgwrote:
>"Default User" <defaultuse...@yahoo.comwrites:
Hongyu wrote:
>I just tried Sebastian's code with adding a line to printf the errno,
>and I got:
>./a.out: could not open ./outdir/mytestout.txt: No such file or
>directory
>errno is 2
>I then changed the fopen line as *FILE *fp = fopen(fname,"w+");
>(replaced w+ to w)
>but still get the same error. What should I do? Thanks a lot.
You should really be posting to a UNIX newsgroup. However, if the
directory doesn't exist, you can NOT create it by opening a file in it.
No matter how much you want to.
>How do you know that? *A conforming C implementation could easily
>create any necessary directories as a side effect of creating a file.
How?
In some system-specific manner.
Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w") could
implicitly invoke the equivalent of "mkdir -p /foo/bar" before
actually creating the file.
That's just one example. *The point is that the C standard doesn't
mention directories at all. *There's nothing in the standard thatsays
an implementation *can't* create a directory as a side effect of
creating a file.
(I'm not aware of any actual implementation that does this.)
--
Keith Thompson (The_Other_Keith) ks...@mib.org *<http://www.ghoti..net/~kst>
Nokia
"We must do something. *This is something. *Therefore, we must do this."
* * -- Antony Jay and Jonathan Lynn, "Yes Minister"- Hide quoted text -
- Show quoted text -
Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w") could
implicitly invoke the equivalent of "mkdir -p /foo/bar" before
actually creating the file.
Thanks everyone's help. The discussion really helps, not only just on
my specific question, but also on the good coding styles etc. I think
what you mentioned here is what I tried in the beginning, but
unfortunately it didn't work, unless i create the directory first. I
am als in a Unix-like system (Linux). I think as people suggested
here, "POSIX" functions are way to go. I will study it more and try
it, and let people know the result after the testing.- Hide quoted text -
- Show quoted text -
The discussion is really helpful and interesting. Thanks everyone's
help again. For some unknown reasons, my questioning post was not
appeared in the unix.programmer group discussion board. But from the
suggestions here, I got the code to work. Just to let people with
similar questions know how to solve the problem, here is the code I
used and POISX is the way to go. *It should be mentioned that multi-
level subdirectories can only be created in the code recursively or
the parent directory is exist and writtable first (i didn't do
recursive coding in the code here).
#include <stdio.h>
#include <errno.h>
#include <error.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main(void)
{
* *char fname[40] = "mytestout.txt"; *//filename
* *//char fpath[40] = "./testdir1/testdir2"; // filepath, doesn'twork
unless testdir1 is exist and writable
* *char fpath[40] = "./testdir1"; // filepath, worked!
* *//char fpath[40] = "."; *//filepath. curent directory. worked!
* *char wholename[100]; //filename with full path
* *int last;
* *last = (int)strlen(fpath)-1; // last char of path
* *//make sure the path is ended with '/'
* *if ((last >= 0) && (fpath[last] != '/'))
* *{
* * * last++;
* * * fpath[last] = '/'; // append '\' at the last of path
* * * fpath[last+1] = '\0'; // terminate the path char string
* *}
* *strcpy(wholename, fpath);
* *strcat(wholename, fname);
* *// create the directory if it is not exist
* *if(access(fpath, F_OK) != 0) // directory nonexist
* *{ * * * * * * * * * * * * * *// actually I don't need to check this
* * * * * * * * * * * * * * * *// because the man mkdir says 'create a
directory
* * * * * * * * * * * * * * * *// if itis non-exist'. But to make
sure, keep it here
* * * // create the directory with read/write/search permissions for
owner and group,
* * * // and with read/search permissions for others
* * * if(mkdir(fpath,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
* * * {
* * * * printf("Failed to create directory %s\n", fpath);
* * * * return EXIT_FAILURE;
* * * }
* *}
* *// write to file whose name is spcified with full path
* *FILE *fp = fopen(wholename, "w");
* * if (fp == NULL)
* *{
* * * error(0, errno, "could not open %s", fname);
* * * exit(EXIT_FAILURE);
* *}
* *else
* *{
* * * fprintf(fp, "This is just a test!");
* * * fclose(fp);
* *}
* *return EXIT_SUCCESS;
}- Hide quoted text -
- Show quoted text -- Hide quoted text -
- Show quoted text -

Sorry, the code didn't appear 100% right after the posting since the
comment lines get adjusted. Here is after the re-adjusting to make it
right:

#include <stdio.h>
#include <errno.h>
#include <error.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

int main(void)
{
* *char fname[40] = "mytestout.txt"; *//filename
* *//char fpath[40] = "./testdir1/testdir2"; // filepath, doesn't work
unless testdir1 is exist and writable
* *char fpath[40] = "./testdir1"; // filepath, worked!
* *//char fpath[40] = "."; *//filepath. curent directory. worked!
* *char wholename[100]; //filename with full path
* *int last;

* *last = (int)strlen(fpath)-1; // last char of path

* *//make sure the path is ended with '/'
* *if ((last >= 0) && (fpath[last] != '/'))
* *{
* * * last++;
* * * fpath[last] = '/'; // append '\' at the last of path
* * * fpath[last+1] = '\0'; // terminate the path char string
* *}

* *strcpy(wholename, fpath);

* *strcat(wholename, fname);

* *// create the directory if it is not exist
* *if(access(fpath, F_OK) != 0) // directory nonexist
* *{ * * * * * * * * * * * * * *// actually I don't need to check
this
* * * * * * * * * * * * * * * *// becausethe man mkdir says 'create a
directory
* * * * * * * * * * * * * * * *// if it is non-exist'. But to make
sure, keep it here

* * * // create the directory with read/write/search permissions for
owner and group,
* * * // and with read/search permissions for others
* * * if(mkdir(fpath,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
* * * {
* * * * printf("Failed to create directory %s\n", fpath);
* * * * return EXIT_FAILURE;
* * * }
* *}

* *// write to file whose name is spcified with full path
* *FILE *fp = fopen(wholename, "w");
* * if (fp == NULL)
* *{
* * * error(0, errno, "could not open %s", fname);
* * * exit(EXIT_FAILURE);
* *}
* *else
* *{
* * * fprintf(fp, "This is just a test!");
* * * fclose(fp);
* *}

* *return EXIT_SUCCESS;

}- Hide quoted text -

- Show quoted text -- Hide quoted text -

- Show quoted text -
I adjusted above, but after posting, the comment line were not so
correct again. Anyway, the code is working just ignore those comments.
Aug 12 '08 #38

P: n/a
Hongyu wrote:
>s0s...@gmail.com writes:
.... snip ...
>>
>>Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w")
could implicitly invoke the equivalent of "mkdir -p /foo/bar"
before actually creating the file.

Thanks everyone's help. The discussion really helps, not only
just on my specific question, but also on the good coding styles
etc. I think what you mentioned here is what I tried in the
beginning, but unfortunately it didn't work, unless i create the
directory first. I am als in a Unix-like system (Linux). I think
as people suggested here, "POSIX" functions are way to go. I will
study it more and try it, and let people know the result after
the testing.
Unless you have specific reasons for needing to use POSIX
functions, you should stick to the standard C functions. Most of
the time the standard functions will be adequate, and in some cases
the results will be more efficient. Using things outside the C
standard always reduces your portability.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
Aug 12 '08 #39

P: n/a
Hongyu said:

<snip>
I adjusted above, but after posting, the comment line were not so
correct again. Anyway, the code is working just ignore those comments.
You can skip around that problem completely, by using /* this style of
comment because, when you do, word wrap doesn't actually matter. */

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Aug 12 '08 #40

P: n/a
On 12 Aug 2008 at 21:49, CBFalconer wrote:
Unless you have specific reasons for needing to use POSIX
functions,
The OP needs to create a directory in a UNIXy operating system. Using
the functions provided by POSIX is the best way to do this by a country
mile.
you should stick to the standard C functions. Most of the time the
standard functions will be adequate, and in some cases the results
will be more efficient.
Which "standard" function is adequate in this case? (hint: none)
Using things outside the C standard always reduces your portability.
You are letting the tail wag the dog. In real life, there's something
you need to get done and you try to do it as portably as possible. Your
attitude is instead that whatever you do must be portable to a 1970s
mainframe or an embedded system controlling a wristwatch, even if that
means you can't actually fulfill your objectives.

But it's hopeless arguing with you - you're a silly old fart who can't
be reasoned with.

Aug 12 '08 #41

P: n/a
Hongyu <ho*******@yahoo.comwrites:

<snip>
... For some unknown reasons, my questioning post was not
appeared in the unix.programmer group discussion board.
For your information: one question did appear in comp.unix.programmer
and got three replies and a clarification. You asked a specific
question that got answered. A more open question might have got
better answers.

--
Ben.
Aug 13 '08 #42

P: n/a
On Aug 12, 4:49*pm, CBFalconer <cb********@yahoo.comwrote:
Hongyu wrote:
s0s...@gmail.com writes:

... snip ...
>Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w")
could implicitly invoke the equivalent of "mkdir -p /foo/bar"
before actually creating the file.
Thanks everyone's help. The discussion really helps, not only
just on my specific question, but also on the good coding styles
etc. I think what you mentioned here is what I tried in the
beginning, but unfortunately it didn't work, unless i create the
directory first. I am als in a Unix-like system (Linux). I think
as people suggested here, "POSIX" functions are way to go. I will
study it more and try it, and let people know the result after
the testing.

Unless you have specific reasons for needing to use POSIX
functions, you should stick to the standard C functions. *Most of
the time the standard functions will be adequate, and in some cases
the results will be more efficient. *Using things outside the C
standard always reduces your portability.
LOL. Portability? What would that portable equivalent be?

Sebastian

Aug 13 '08 #43

P: n/a
CBFalconer <cb********@yahoo.comwrites:
Hongyu wrote:
>>s0s...@gmail.com writes:
... snip ...
>>>
Assuming a Unix-like system, fopen("/foo/bar/newfile.txt", "w")
could implicitly invoke the equivalent of "mkdir -p /foo/bar"
before actually creating the file.

Thanks everyone's help. The discussion really helps, not only
just on my specific question, but also on the good coding styles
etc. I think what you mentioned here is what I tried in the
beginning, but unfortunately it didn't work, unless i create the
directory first. I am als in a Unix-like system (Linux). I think
as people suggested here, "POSIX" functions are way to go. I will
study it more and try it, and let people know the result after
the testing.

Unless you have specific reasons for needing to use POSIX
functions, you should stick to the standard C functions. Most of
the time the standard functions will be adequate, and in some cases
the results will be more efficient. Using things outside the C
standard always reduces your portability.
No, it does not *always* reduce your portability.

Or do you claim that
system("mkdir foo");
is more portable than
mkdir("foo", 0777);
?

The OP needs to create a directory. That's a specific reason to use
POSIX functions.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 13 '08 #44

P: n/a
Keith Thompson wrote:
CBFalconer <cb********@yahoo.comwrites:
.... snip ...
>
>Unless you have specific reasons for needing to use POSIX
functions, you should stick to the standard C functions. Most
of the time the standard functions will be adequate, and in some
cases the results will be more efficient. Using things outside
the C standard always reduces your portability.

No, it does not *always* reduce your portability.

Or do you claim that
system("mkdir foo");
is more portable than
mkdir("foo", 0777);

The OP needs to create a directory. That's a specific reason to
use POSIX functions.
That is covered above by 'specific reasons'. However the program
without any mkdir will compile and execute on more systems than the
program with mkdir. That's increased portability.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
Aug 13 '08 #45

P: n/a
On Aug 12, 9:29 pm, CBFalconer <cb********@yahoo.comwrote:
Keith Thompson wrote:
CBFalconer <cb********@yahoo.comwrites:

... snip ...
Unless you have specific reasons for needing to use POSIX
functions, you should stick to the standard C functions. Most
of the time the standard functions will be adequate, and in some
cases the results will be more efficient. Using things outside
the C standard always reduces your portability.
No, it does not *always* reduce your portability.
Or do you claim that
system("mkdir foo");
is more portable than
mkdir("foo", 0777);
The OP needs to create a directory. That's a specific reason to
use POSIX functions.

That is covered above by 'specific reasons'. However the program
without any mkdir will compile and execute on more systems than the
program with mkdir. That's increased portability.
....by your definition of "portability." IMO, it's better to have the
program *not* compile and tell me that something doesn't work, instead
of having it compile and shipping something that will produce an
utterly and completely useless result when executed.

Sebastian

Aug 13 '08 #46

P: n/a
CBFalconer wrote:
Keith Thompson wrote:
>CBFalconer <cb********@yahoo.comwrites:
.... snip ...
>>Unless you have specific reasons for needing to use POSIX
functions, you should stick to the standard C functions. Most
of the time the standard functions will be adequate, and in some
cases the results will be more efficient. Using things outside
the C standard always reduces your portability.
No, it does not *always* reduce your portability.

Or do you claim that
system("mkdir foo");
is more portable than
mkdir("foo", 0777);

The OP needs to create a directory. That's a specific reason to
use POSIX functions.

That is covered above by 'specific reasons'. However the program
without any mkdir will compile and execute on more systems than the
program with mkdir. That's increased portability.
Portability is inversely proportional to usability...

--
Ian Collins.
Aug 13 '08 #47

P: n/a
s0****@gmail.com wrote:
CBFalconer <cb********@yahoo.comwrote:
>Keith Thompson wrote:
>>CBFalconer <cb********@yahoo.comwrites:

... snip ...
>>>Unless you have specific reasons for needing to use POSIX
functions, you should stick to the standard C functions. Most
of the time the standard functions will be adequate, and in some
cases the results will be more efficient. Using things outside
the C standard always reduces your portability.

No, it does not *always* reduce your portability.

Or do you claim that
system("mkdir foo");
is more portable than
mkdir("foo", 0777);

The OP needs to create a directory. That's a specific reason to
use POSIX functions.

That is covered above by 'specific reasons'. However the program
without any mkdir will compile and execute on more systems than
the program with mkdir. That's increased portability.

...by your definition of "portability." IMO, it's better to have
the program *not* compile and tell me that something doesn't work,
instead of having it compile and shipping something that will
produce an utterly and completely useless result when executed.
You don't seem to pick up too quickly. No, the simple thing is for
the user to have a suitable directory structure in existance before
running the program (assuming the system has directories). This
totally removes any urge to have/use a mkdir function.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

Aug 13 '08 #48

P: n/a
On Aug 12, 11:17 pm, CBFalconer <cb********@yahoo.comwrote:
s0****@gmail.com wrote:
CBFalconer <cb********@yahoo.comwrote:
Keith Thompson wrote:
CBFalconer <cb********@yahoo.comwrites:
... snip ...
>>Unless you have specific reasons for needing to use POSIX
functions, you should stick to the standard C functions. Most
of the time the standard functions will be adequate, and in some
cases the results will be more efficient. Using things outside
the C standard always reduces your portability.
>No, it does not *always* reduce your portability.
>Or do you claim that
system("mkdir foo");
is more portable than
mkdir("foo", 0777);
>The OP needs to create a directory. That's a specific reason to
use POSIX functions.
That is covered above by 'specific reasons'. However the program
without any mkdir will compile and execute on more systems than
the program with mkdir. That's increased portability.
...by your definition of "portability." IMO, it's better to have
the program *not* compile and tell me that something doesn't work,
instead of having it compile and shipping something that will
produce an utterly and completely useless result when executed.

You don't seem to pick up too quickly. No, the simple thing is for
the user to have a suitable directory structure in existance before
running the program (assuming the system has directories). This
totally removes any urge to have/use a mkdir function.
Oh, I thought you were saying yes to what Keith Thompson asked
(whether system("mkdir foo") was more portable than mkdir("foo",
0777)).

But requiring the user to create the directory him/herself just
because the program can't do it portably isn't something acceptable
out there in the "real world."

Sebastian

Aug 13 '08 #49

P: n/a
On 13 Aug 2008 at 4:34, s0****@gmail.com wrote:
On Aug 12, 11:17 pm, CBFalconer <cb********@yahoo.comwrote:
>You don't seem to pick up too quickly. No, the simple thing is for
the user to have a suitable directory structure in existance before
running the program (assuming the system has directories). This
totally removes any urge to have/use a mkdir function.

But requiring the user to create the directory him/herself just
because the program can't do it portably isn't something acceptable
out there in the "real world."
As you're discovering, "Chuck" neither knows nor cares about the "real
world". And why would he? It all seems so far away when you're sitting
amongst a group of incontinent crones in an old folks home.

I'd love to see CBF try to write code in the real world...

Customer: I see the code we contracted you for is finished.
CBF: Yes sir. It's 100% portable.
Cust: It doesn't meet our specification, though.
CBF: No sir, that would have meant using a POSIX function.
Cust: But the spec is what we wanted, damn it.
CBF: This code will run inside your portable travel radio too! It's
portable!
Cust: But it doesn't do what we wanted.
CBF: That's the price you pay for portability.
Cust: But having the code do what I wanted is more important to me than
portability.
CBF: You're mistaken. There's nothing more important than portability.
Cust: ?*#!
CBF: Why don't you write a shell script to do half the stuff my program
was meant to do, and make sure you run it before my program? After all,
my program needs to be in ISO C or else the ISO Standard makes no
guarantees about it.
Cust: ?*#?*#?*#?*#?*#!!!!!?*#!

Aug 13 '08 #50

65 Replies

This discussion thread is closed

Replies have been disabled for this discussion.