473,765 Members | 2,061 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem opening a file

I'm trying to run this code under windows xp sp2 using codeblocks v1.0
compiler with great difficulty.Ther e is no problem with running this
under KDevelop in linux. Any help would be greatly appreciated.
Enter an interesting string.
Too many cooks spoil the broth
Error opening C:\myfile.txt for writing. Program termnated.
This application has requested the Runtime to terminate it in an
unusual way.
Please contact the application's support team for more information.

Press ENTER to continue.
*************** *************** *************** *************** *************** ******
#include <stdio.h>
#include <stdlib.h>

int main()
{
char mystring[80];
int i = 0;
int lstr = 0;
int mychar = 0;
FILE *pfile = NULL;
char *filename = "C:\\myfile.txt ";

printf("\nEnter an interesting string.\n");
gets(mystring);

pfile = fopen(filename, "w");
if(pfile == NULL)
{
printf("Error opening %s for writing. Program termnated.",
filename);
abort();
}

lstr = strlen(mystring );
for(i=lstr -1; i >= 0; i--)
fputc(mystring[i], pfile);

fclose(pfile);

/*ope file for reading*/
pfile = fopen(filename, "r");
if(pfile == NULL)
{
printf("Error opening %s for reading. Program terminated.",
filename);
abort();
}

/*Read a character from the file and display it*/
while((mychar = fgetc(pfile)) != EOF)
putchar(mychar) ;
putchar('\n');

fclose(pfile);
remove(filename );

return 0;
}

Feb 12 '06 #1
11 3611

<al****@xtra.co .nz> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
I'm trying to run this code under windows xp sp2 using codeblocks v1.0
compiler with great difficulty.Ther e is no problem with running this
under KDevelop in linux. Any help would be greatly appreciated.
Enter an interesting string.
Too many cooks spoil the broth
Error opening C:\myfile.txt for writing. Program termnated.
This application has requested the Runtime to terminate it in an
unusual way.
Please contact the application's support team for more information.


I don't see anything wrong with the code (other than the
use of the inherently dangerous 'gets()' function).

For some reason, the host system has refused to open your
output file. C can only tell you if the operation succeeded
or not, but not *why* it didn't succeed.

Some possible reasons for 'fopen()' to fail on Windows:
1. Disk is full
2. Disk failure
3. Insufficient access rights.
4. Disk is inaccessible (e.g. disconnected from a network)
5. File is already opened by another process, but not 'shared'.

How to deal with any of these issues (or others) is not
covered by the C language.

The message about 'terminate in an unusual way' reflects the
fact that you called the standard function 'abort()', which
is indeed not the 'normal' way to terminate a C program.
The 'normal' way is to have function 'main()' return control
to the host system. (Also see 'exit()')

-Mike
Feb 12 '06 #2
In article <11************ *********@f14g2 000cwb.googlegr oups.com>,
<al****@xtra.co .nz> wrote:
I'm trying to run this code under windows xp sp2 using codeblocks v1.0
compiler with great difficulty.Ther e is no problem with running this
under KDevelop in linux. Any help would be greatly appreciated. Enter an interesting string.
Too many cooks spoil the broth
Error opening C:\myfile.txt for writing. Program termnated.
This application has requested the Runtime to terminate it in an
unusual way. char *filename = "C:\\myfile.txt "; pfile = fopen(filename, "w");
if(pfile == NULL)
{
printf("Error opening %s for writing. Program termnated.",
filename);
abort();
}


The rest of the program does not matter, as it is clear that in
the fault case the abort() is what is terminating the program.

So you have a situation where under true windows, C:\myfile.txt
cannot be opened for writing, but under an emulator (?),
KDevelop in linux, it can be.

My guess would be that in the real windows XP system, your process
does not have authorization to create files directly in C:\
and that in KDevelop either there is no file permission testing
or else that the emulated C:\ is a directory that you happen to
have access to.

I would suggest replacing the printf() with perror() as that will
print out the error reason. perror() does not support %s formats
though, so either work around that or include <errno.h> and
use strerror().
--
All is vanity. -- Ecclesiastes
Feb 12 '06 #3
al****@xtra.co. nz writes:
I'm trying to run this code under windows xp sp2 using codeblocks v1.0
compiler with great difficulty.Ther e is no problem with running this
under KDevelop in linux. Any help would be greatly appreciated.
I have no idea what "codeblocks " is, but if your problem actually
depends on that, then it's not something we can help you with here.
Enter an interesting string.
Too many cooks spoil the broth
Error opening C:\myfile.txt for writing. Program termnated.
This application has requested the Runtime to terminate it in an
unusual way.
Please contact the application's support team for more information.

Press ENTER to continue.
I don't see any serious problems that would necessarily explain the
symptoms you're seeing. I do see some serious problems, though.

The "This application has requested ..." message is presumably caused
by the call to abort(). There's no need to terminate the program so
drastically; exit(EXIT_FAILU RE) is just fine.

Error messages are normally printed to stdout, not stderr (but that's
not required).
#include <stdio.h>
#include <stdlib.h>

int main()
{
char mystring[80];
int i = 0;
int lstr = 0;
int mychar = 0;
FILE *pfile = NULL;
char *filename = "C:\\myfile.txt ";
Obviously this file name is non-portable. On Linux, your program
would probably create a file in the current directory whose name is
C:\myfile.txt
Check whether that's a valid file name in the environment in which
your program runs. Do you have write permission on C:\? What happens
if you change the file name to just "myfile.txt " (i.e., create it in
the current directory)?

Note that any considerations about directories, path names, and the
meaning of a file name is system-specific. If you're still having
trouble, you might try a system-specific newsgroup.
printf("\nEnter an interesting string.\n");
gets(mystring);
Never use gets(). Never. Never ever. For all practical purposes, it
*cannot* be used safely. (There are obscure circumstances in which it
can be used safely, but if you know enough to figure that out you know
enough not to use gets() anyway.)

See <http://www.c-faq.com/stdio/getsvsfgets.htm l>.
pfile = fopen(filename, "w");
if(pfile == NULL)
{
printf("Error opening %s for writing. Program termnated.",
filename);
On some systems, a failing fopen() *might* set a meaningful value for
errno. Try setting errno to 0 before the fopen() call, and checking
its value after the call; use perror() to print an error message
*only* if errno!=0. The result may or may not be meaningful (the
standard doesn't say anything about fopen()'s effect on errno). See
also <http://www.c-faq.com/misc/errno.html>.
abort();
}

lstr = strlen(mystring );
You use strlen(), but you don't have a "#include <string.h>". Turn up
the warning level on your compiler; it should be able to warn you
about this kind of thing.
for(i=lstr -1; i >= 0; i--)
fputc(mystring[i], pfile);

fclose(pfile);
You've just created a text file that isn't terminated by a new-line
character. Some implementations might require a new-line at the end
of every text file. (Yours probably doesn't, but if you care about
portability you should make sure it's there anyway).
/*ope file for reading*/
pfile = fopen(filename, "r");
if(pfile == NULL)
{
printf("Error opening %s for reading. Program terminated.",
filename);
abort();
}

/*Read a character from the file and display it*/
while((mychar = fgetc(pfile)) != EOF)
putchar(mychar) ;
putchar('\n');

fclose(pfile);
remove(filename );
Misleading indentation. Only the "putchar(mychar );" is part of the
while loop. With correct indentation:

while((mychar = fgetc(pfile)) != EOF)
putchar(mychar) ;
putchar('\n');

fclose(pfile);
remove(filename );

Personally, I always use braces with control structures, even when
they're not required, so I'd write it as:

while((mychar = fgetc(pfile)) != EOF) {
putchar(mychar) ;
}
putchar('\n');

fclose(pfile);
remove(filename );
return 0;
}


Since you're having a problem on the initial fopen() call, the rest of
your program isn't relevant to the problem. You could have narrowed
your program down to something much smaller before posting.

(The program uses a temporary file to reverse a string. I'm sure
you're aware that there are much easier ways to reverse a string.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 12 '06 #4
>I would suggest replacing the printf() with perror() as that will
print out the error reason. perror() does not support %s formats
though, so either work around that or include <errno.h> and
use strerror().


I'll try the suggestions above and see how it goes. Thanks!

Feb 12 '06 #5
Keith great advice!! In my excitement to post i forgot to mention that
i modified the code to point to /home/user/text.txt.
Never use gets(). Never. Never ever. For all practical purposes, it
*cannot* be used safely. (There are obscure circumstances in which it
can be used safely, but if you know enough to figure that out you know
enough not to use gets() anyway.)


Ignorance is bliss!! I will go back to the drawing board atleast with
something to think about. Thanks for that.

Feb 12 '06 #6
>Some possible reasons for 'fopen()' to fail on Windows:
1. Disk is full
2. Disk failure
3. Insufficient access rights.
4. Disk is inaccessible (e.g. disconnected from a network)
5. File is already opened by another process, but not 'shared'.
Double checked all disk/s have plenty of space with the same error
popping up under different IDEs(Visual C++ .net, Dev C++)on more than
one PC, and using admin account didn't have any effect. Also tested on
PCs running locally without networking and couldn't really see anything
that couldve interfered with the file opening other than the shoddy
coding.
The 'normal' way is to have function 'main()' return control
to the host system. (Also see 'exit()')

thanks for that advice taken.

Feb 12 '06 #7
al****@xtra.co. nz wrote:
[...]
Error opening C:\myfile.txt for writing. Program termnated. [...] pfile = fopen(filename, "w");
if(pfile == NULL)
{
printf("Error opening %s for writing. Program termnated.",
filename);
Try changing the above to:

perror(filename );

Although, as I understand it, the standard does not require fopen() to
set errno, your system probably does, so the above will probably print
the filename and the reason for the failure.

If, for some reason, your system doesn't set errno, then you'll have to
do some further investigation to find the cause.
abort();
}

[...]
--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Feb 12 '06 #8
Walter Roberson wrote:
[...]
So you have a situation where under true windows, C:\myfile.txt
cannot be opened for writing, but under an emulator (?),
KDevelop in linux, it can be.

[...]

FYI -- "C:\myfile. txt" is a valid filename under Linux, so there may not
be any emulator involved. (Why anyone would want such a filename under
Linux is a separate issue.)

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Feb 12 '06 #9
Kenneth Brody wrote:
Walter Roberson wrote:
[...]
So you have a situation where under true windows, C:\myfile.txt
cannot be opened for writing, but under an emulator (?),
KDevelop in linux, it can be.

[...]

FYI -- "C:\myfile. txt" is a valid filename under Linux, so there
may not be any emulator involved. (Why anyone would want such a
filename under Linux is a separate issue.)


Is an escaped m a legitimate string character? I could understand
your statement about "C:\noxious.txt ", "C:\bullturd.tx t", or
"C:\ambivalent. txt". Use of "C:\truncate.tx t" is likely to cause
future difficulties.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Feb 12 '06 #10

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

Similar topics

7
12658
by: Graham Taylor | last post by:
I've tried posting this in the 'microsoft.public.access' but I will post it here also, as I think it might be the webserver which is causing my problem. --------- I have an Access 2003 database which is in the "fpdb" folder of my webserver. Its located there so that I can use asp to build a web-based front-end for users to read the database - http://www.nist.ac.th/maths/test1.asp The MBD file is edited using Access (2003) and opening...
1
4401
by: Alfons | last post by:
Hello, I have build a program that can do file transferring between a Windows XP computer and a DOS computer via a serial port. The Windows program I have build in C++ with Visual Studio 6.0. The DOS program I made in Turbo C++ 3.0. At this moment I am in a test phase of sending files and directories. The code I am using in DOS to open a file for writing looks like this (forgive me the typos, since I only have my source code at work...
5
4914
by: John Morgan | last post by:
I am using the following link to download a file of about 50k <a target= "_blank" href="http://www.bsecs.org.uk/ExecDocs/documentStore/elfridaWord.doc">open file</a> If I save the file to hard disk there is no problem/ if, in response to the menu which appears before downloading, I opt to open the doc file immediately then I get a problem.
8
1719
by: beginner10 | last post by:
Hello! Can anyone help me? This code doesnt work. Where is the problem? Inside the files mata and matb there is (should be) 10*10 matrix. It should count a sum to new matrix. It does not work. Where is the problem? #include <stdio.h> main()
0
2033
by: anide | last post by:
Hi all I’ve some problem, I’m trying to converting a sorting algorithm from C++ to C#. In C++ I’ve compiled it using MSVC and its working properly, and in C# I’m using .NET Framework 2.0 (Visual Studio 2005). The problem occurred when I trying to opening and reading file: ============= C++ ============= void LoadSourceFile(char * fileName, unsigned char * data, int length)
0
1475
by: nt91rx78 | last post by:
Our college changes 18 weeks semester to 16 semester, so our CS professor cannot finish teaching the last important chapter which is related with my problw\em. This is program C problem Anyone can help me with this problem, please!!!!!!!!! This is the problem: 3. Several input text files have been provided as input to your program. a) Write a function to combine these files into a single file. b) Write a function to take care of...
5
1919
by: GeekBoy | last post by:
Thanks for the help obnoxious. Reading in the rest of the line with "getline" worked great and now the averages work. Now for the new problem. Program on first run works flawlessly. Next runs enter in some data I don;t know what instead of the data in the file. Tried closing and opening file again, but it's not working. #include<iomanip> #include<fstream>
3
4318
by: =?iso-8859-9?B?RGlu52F5IEFr5/ZyZW4=?= | last post by:
When I execute the following code #include <stdio.h> #include <stdlib.h> int main(void) { FILE *bmp; bmp = fopen("deneme.bmp","w"); fputc(10,bmp);
1
1830
by: Sanjeeva K kanakam | last post by:
Hi all, I am developing one application. In that i have created on report file which contains tables, titles and tree view list also by using HTML tags. I am opening this file in my application it self as another window. There is no problem in opening this file if the file is small. If the file is big(here i mean to say if number of tables present in this file)then while opening this file my application is displaying a message "Cannot create...
0
9404
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10168
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10008
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9837
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6651
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5279
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3929
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.