473,503 Members | 1,673 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to write to a file including directory name in C?

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;

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
12 8514
On Aug 11, 5:26*pm, 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:

#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;

* *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
One more information. Actually, my code in the line of fclose has been
corrected as fclose(fp), but I still got error of "Failed to open
file ./outdir/mytestout.txt
Segmentation fault."

Aug 11 '08 #2
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, [..]
Try news:comp.lang.c or any of the numerous Unix newsgroups. Generally,
relative paths should be avoided.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 11 '08 #3
On Aug 11, 5:48*pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
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, [..]

Try news:comp.lang.c or any of the numerous Unix newsgroups. *Generally,
relative paths should be avoided.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Thanks. I will try that.
Aug 11 '08 #4
"Hongyu" <ho*******@yahoo.comwrote in message
news:56**********************************@26g2000h sk.googlegroups.com...
On Aug 11, 5:48 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
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, [..]

Try news:comp.lang.c or any of the numerous Unix newsgroups. Generally,
relative paths should be avoided.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Thanks. I will try that.

---------

Incidnetly, you shoudl be in the current directory alrady, so have you tried
"outdir/mytestout.txt"
and have you made sure that outdir exists?
Aug 12 '08 #5
On Aug 11, 11:48 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
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,
[..]
Try news:comp.lang.c or any of the numerous Unix newsgroups.
Whether Unix or Windows (or C or C++), he might start by
ensuring that the directories exist. If there's no directory
outdir in the current directory, his fopen is going to fail.
(Of course, if he wants to create the directory, he'll have to
ask in the OS group, because there's no way to create a
directory portably.)
Generally, relative paths should be avoided.
Just curious, but why? I tend to prefer relative paths to
absolute for most things. Obviously, it all depends on what
you're doing, but would you like it if your compiler put the
object files in some absolute path?

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Aug 12 '08 #6
Hongyu wrote:
strcpy(fname,"./outdir/mytestout.txt");
fp=fopen(fname, "w");
The "./" part is not necessary (and I don't even know if it's
portable). Separating directories with '/' should be rather portable (at
least it works in windows as well as unix, although I don't really know
if it's standard).

You should really use the perror() to print the proper error message
in a case like this. It can be much more informative than just a "failed
to open" generic message. It can be used like this:

if(fp == NULL)
{
fprintf(stderr, "Failed to open file ");
perror(fname);
}

From the many possibilities for the error to happen, two are most likely:

1) The directory 'outdir' doesn't exist in the current directory.
fopen() will not create it if it doesn't exist.

2) You don't have write permissions to that directory.
Aug 12 '08 #7
James Kanze wrote:
On Aug 11, 11:48 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
>[..]
Generally, relative paths should be avoided.

Just curious, but why? I tend to prefer relative paths to
absolute for most things. Obviously, it all depends on what
you're doing, but would you like it if your compiler put the
object files in some absolute path?
Well, I've seen programs that had problems that can be distilled to

set_current_directory(somepath);
some_3rd_party_function();
// assume current directory is still 'somepath'
open_file(relativepath);

You cannot imagine the surprise on the faces of the developer who wrote
that code when he finds out that in a patched version of the 3rd party
library the current directory is changed to something else, which is not
documented and not reported in the release notes. In such case you
cannot go wrong with

some_3rd_party_function();
open_file(make_absolute_path(somepath, relativepath));

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 12 '08 #8
On Aug 12, 4:07 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
James Kanze wrote:
On Aug 11, 11:48 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
[..]
Generally, relative paths should be avoided.
Just curious, but why? I tend to prefer relative paths to
absolute for most things. Obviously, it all depends on what
you're doing, but would you like it if your compiler put the
object files in some absolute path?
Well, I've seen programs that had problems that can be
distilled to
set_current_directory(somepath);
some_3rd_party_function();
// assume current directory is still 'somepath'
open_file(relativepath);
You cannot imagine the surprise on the faces of the developer
who wrote that code when he finds out that in a patched
version of the 3rd party library the current directory is
changed to something else, which is not documented and not
reported in the release notes.
There's only so much you can (or should) do to fight stupidity.
And libraries that change the current directory without
resetting it fall into that category. If you really can't avoid
using the library, you should at least wrap it, saving the
current directory when you call it, and restoring it when you
return. (To repeat my question: would you like it if your
compiler used this library, and ended up putting the generated
object files where ever the library went to.)
In such case you cannot go wrong with
some_3rd_party_function();
open_file(make_absolute_path(somepath, relativepath));
Provided you can obtain an absolute path. But it sounds like
two wrongs trying to make a right to me.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Aug 12 '08 #9
On Aug 12, 12:35 pm, Juha Nieminen <nos...@thanks.invalidwrote:
Hongyu wrote:
strcpy(fname,"./outdir/mytestout.txt");
fp=fopen(fname, "w");
The "./" part is not necessary (and I don't even know if it's
portable).
In certain contexts (not here), at least under Unix, the "./"
has the effect of turning off searching in a path. (dlopen
comes to mind.) Thus, some programmers get used to using it,
and it doesn't hurt.
Separating directories with '/' should be rather portable (at
least it works in windows as well as unix, although I don't
really know if it's standard).
It's standard... Posix. The C++ standard doesn't even
guarantee directories.
You should really use the perror() to print the proper error
message in a case like this. It can be much more informative
than just a "failed to open" generic message.
I would prefer stderror. It gives you more options with regards
to formatting.
It can be used like this:
if(fp == NULL)
{
fprintf(stderr, "Failed to open file ");
Except that if there is a problem with this fprint, the errno
used by perror after it will not reflect the original problem.
I'd use something like:

int errorCode = errno ;
std::cerr << "Could not open " << fname << ", error was: "
<< stderror( errorCode ) << std::endl ;

(In C:
int errorCode = errno ;
fprintf( "Could not open %s, error was: %s\n",
fname, stderror( errorCode ) ) ;
. But frankly, I'd prefer to avoid it.)
perror(fname);
}
From the many possibilities for the error to happen, two are most likely:
1) The directory 'outdir' doesn't exist in the current directory.
fopen() will not create it if it doesn't exist.
2) You don't have write permissions to that directory.
3) A file with the same name already exists, and you don't have
access rights to it.

4) There are no more inodes left on the device. (I've been hit
by that one a couple of times recently.)

etc., etc.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Aug 12 '08 #10
James Kanze wrote:
I would prefer stderror.
Don't you mean strerror?
Aug 12 '08 #11
James Kanze wrote:
[...]
>Well, I've seen programs that had problems that can be
distilled to
> set_current_directory(somepath);
some_3rd_party_function();
// assume current directory is still 'somepath'
open_file(relativepath);
>You cannot imagine the surprise on the faces of the developer
who wrote that code when he finds out that in a patched
version of the 3rd party library the current directory is
changed to something else, which is not documented and not
reported in the release notes.

There's only so much you can (or should) do to fight stupidity.
And libraries that change the current directory without
resetting it fall into that category.
Not exactly on-topic, but this reminds me of one of those sentences
you can often see in mail and Usenet signatures:

It is impossible to make anything foolproof because fools are
so ingenious.

In the case above, anyway, it's hard to discern stupidity from
incompetence... touching a global entity without restore...

--
Gennaro Prota | <https://sourceforge.net/projects/breeze/>
Do you need expertise in C++? I'm available.
Aug 12 '08 #12
On Aug 12, 7:49 pm, Juha Nieminen <nos...@thanks.invalidwrote:
James Kanze wrote:
I would prefer stderror.
Don't you mean strerror?
Actually, std::strerror(), in C++:-). But yes. I don't know
why, but that seems to be a common typo with me.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Aug 13 '08 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
8750
by: haynesc | last post by:
Hi, I'm having a problem where when trying to open a file in write mode, I get an IOError stating no such file or directory. I'm calling an external program which takes an input file and...
8
17430
by: Glenn A. Harlan | last post by:
Why am I receiving the below error when calling - Path.GetTempFileName() The directory name is invalid. Description: An unhandled exception occurred during the execution of the current web...
2
1998
by: Alexander Keßler | last post by:
Hi, I want to programm some kind of Explorer like the Windows Explorer. And I want to know how can i get the same Icons/Symbols for the files and directories like the Windows Explorer uses. ...
1
4258
by: Vikram | last post by:
I have suddenly started getting this errorin all my ASP.NET applications when I try to open any aspx page. Compiler Error Message: CS0016: Could not write to output file...
65
5019
by: Hongyu | last post by:
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...
0
7271
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7319
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7449
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5570
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4666
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3160
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3149
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
373
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.