473,396 Members | 1,987 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Reading/Writing other files from inside a C program

I am learning C, so I decided to try out r/w-ing to other files. Can
anyone please tell me why I get the following error when running the
program?
Transcript:
Name?
Nikhil R. Mulani
Bus error
Code:

#include <stdio.h>

main()
{
char name[60];
FILE *Fp;

Fp = fopen("/deeter.dat", "w");

printf("Name?\n");
scanf("%s",name);

fprintf(Fp, "Name: %s\n", name);

int fclose( FILE *Fp );
}

Nov 14 '05 #1
16 1311
ex******@gmail.com wrote:
I am learning C, so I decided to try out r/w-ing to other files. Can
anyone please tell me why I get the following error when running the
program?
[...]
scanf("%s",name);
[...]


You miss an "&" before "name".

--
If geiger counter does not click,
the coffee, she is just not thick
Nov 14 '05 #2
thanks!

Nov 14 '05 #3
Sebastian Hungerecker wrote:

ex******@gmail.com wrote:
I am learning C, so I decided to try out r/w-ing to other files. Can
anyone please tell me why I get the following error when running the
program?
[...]
scanf("%s",name);
[...]


You miss an "&" before "name".


I haven't seen the original article, but if name is an array of char,
then prepending & is incorrect. %s matches char *, not char (*)[].

Also, the OP should be aware that scanf("%s", name) opens the program
up to the possibility of a buffer overrun attack.
Nov 14 '05 #4
ex******@gmail.com <ex******@gmail.com> wrote:
I am learning C, so I decided to try out r/w-ing to other files. Can
anyone please tell me why I get the following error when running the
program? Transcript:
Name?
Nikhil R. Mulani
Bus error Code: #include <stdio.h> main()
{
char name[60];
FILE *Fp; Fp = fopen("/deeter.dat", "w"); printf("Name?\n");
scanf("%s",name); fprintf(Fp, "Name: %s\n", name); int fclose( FILE *Fp );
}


There are several problems with your program of different importance.

1) main() is supposed to return an int. While you will get away without
specifying a return type on older compilers (i.e. non-C99) you should
avoid that and use either

int main( void )

or

int main( int argc, char *argv[ ] )

2) You never test if the call of fopen() succeeds. But when it fails
'Fp' will be set to NULL and you can't write to the file.

3) Using scanf() to read in strings is tricky. First of all, when
you just have a "%s" conversion specifier you can't avoid that
the user enters more characters than fit into the buffer into
which the result gets written - and if (s)he does you write past
the end of that buffer, which is a very bad mistake. Thus you
should call it at least with

scanf( "%59s", name );

That way the user can't enter more than 59 characters (you need
the 60th for the final '\0' character).

Another problem is that scanf() stops at white space (i.e spaces,
tabs etc.). This will keep you from entering "Nikhil R. Mulani"
since scanf() will stop reading after the "Nikhil". While that
can be circumvented by using

scanf( "%59[^\n]", name );

it probably is simpler to use fgets() to read in the whole line.

4) Since you didn't check that 'Fp' isn't NULL you might get into
problems with the call of fprintf() - this expects a valid FILE
pointer as the first argument.

5) The line

int fclose( FILE *Fp );

should get the compiler upset (and I strongly doubt that you got
the program compiled in the for you posted it). I guess you want

fclose( Fp );

here - but don't call fclose() when 'Fp' is NULL.

6) Since main() is supposed to return an int your program is missing
a return statement at the end.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #5
Sebastian Hungerecker <se****@web.de> wrote:
ex******@gmail.com wrote:
I am learning C, so I decided to try out r/w-ing to other files. Can
anyone please tell me why I get the following error when running the
program?
[...]
scanf("%s",name);
[...]
You miss an "&" before "name".


No, he definitely doesn't - 'name' is an array of chars and in value
context (like here) it is automatically converted to a pointer to the
first element of the array.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #6
Je***********@physik.fu-berlin.de wrote:
Sebastian Hungerecker <se****@web.de> wrote:
You miss an "&" before "name".


No, he definitely doesn't


You're right. I didn't look/think carefully enough - I'm sorry for the
wrong advice.

--
If geiger counter does not click,
the coffee, she is just not thick
Nov 14 '05 #7
Thank you all. I'll try out these suggestions.

Nov 14 '05 #8
I got it to work, and learned a lot too. thanks again

Nov 14 '05 #9
Sebastian Hungerecker wrote:
ex******@gmail.com wrote:
I am learning C, so I decided to try out r/w-ing to other files. Can
anyone please tell me why I get the following error when running the
program?
[...]
scanf("%s",name);
[...]

You miss an "&" before "name".


You are wrong.
Nov 14 '05 #10
ex******@gmail.com wrote:
thanks!


Don't thank him: he's wrong.
Nov 14 '05 #11
ex******@gmail.com wrote:
I am learning C, so I decided to try out r/w-ing to other files. Can
anyone please tell me why I get the following error when running the
program?
Transcript:
Name?
Nikhil R. Mulani
Bus error
It's hard to say. It's probably not because of the failure to explicitly
state the return type of main as int (required for C99), or
because of the failure to explicitly return a value from main (required
for predictable behavior before C99), or because of the failure to check
that the fopen succeeded, or because of using scanf("%s",... for input
data that *might* contain whitespace. My best guess is ...
Code:

#include <stdio.h>

main()
{
char name[60];
FILE *Fp;
Fp = fopen("/deeter.dat", "w");
printf("Name?\n");
scanf("%s",name);
fprintf(Fp, "Name: %s\n", name);
int fclose( FILE *Fp );
.... this line, which contains a bogus 'int' and 'FILE *', and so looks
like a declaration in the middle of your code. This should, on a
pre-C99 compiler, have resulted in a failure to compile.
}


Here is an example of how you might start to make your code look more
like a real C program. Improvements to my example code are, of course,
possible.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
char name[60];
FILE *Fp;
if (!(Fp = fopen("./deeter.dat", "w"))) {
fprintf(stderr,
"Could not open \"./deeter.dat\" for output.\n");
exit(EXIT_FAILURE);
}
printf("What is your name? ");
fflush(stdout);
if (fgets(name, sizeof name, stdin)) {
char *nl;
if ((nl = strchr(name, '\n')))
*nl = 0;
fprintf(Fp, "Name: %s\n", name);
}
else {
fprintf(stderr, "Arcane input error.\n");
fclose(Fp);
remove("./deeter.dat");
exit(EXIT_FAILURE);
}
fclose(Fp);
return 0;
}
Nov 14 '05 #12
On 26 Feb 2005 17:59:11 GMT, Je***********@physik.fu-berlin.de wrote
in comp.lang.c:
ex******@gmail.com <ex******@gmail.com> wrote:
I am learning C, so I decided to try out r/w-ing to other files. Can
anyone please tell me why I get the following error when running the
program?
Transcript:
Name?
Nikhil R. Mulani
Bus error

Code:

#include <stdio.h>

main()
{
char name[60];
FILE *Fp;

Fp = fopen("/deeter.dat", "w");

printf("Name?\n");
scanf("%s",name);

fprintf(Fp, "Name: %s\n", name);

int fclose( FILE *Fp );
}


There are several problems with your program of different importance.


[snip]
5) The line

int fclose( FILE *Fp );

should get the compiler upset (and I strongly doubt that you got
the program compiled in the for you posted it). I guess you want
You went a little overboard here. The line represents a perfectly
correct prototype for the function fclose(), and a prototype is
perfectly legal at this point in the source code. So it most
certainly should compile, although it doesn't do what the OP expects.
fclose( Fp );

here - but don't call fclose() when 'Fp' is NULL.


The rest of your advice is excellent, of course.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #13
Jack Klein <ja*******@spamcop.net> writes:
On 26 Feb 2005 17:59:11 GMT, Je***********@physik.fu-berlin.de wrote
in comp.lang.c:

[snip]
5) The line

int fclose( FILE *Fp );

should get the compiler upset (and I strongly doubt that you got
the program compiled in the for you posted it). I guess you want


You went a little overboard here. The line represents a perfectly
correct prototype for the function fclose(), and a prototype is
perfectly legal at this point in the source code. So it most
certainly should compile, although it doesn't do what the OP expects.
fclose( Fp );

here - but don't call fclose() when 'Fp' is NULL.


The rest of your advice is excellent, of course.


A prototype is legal at that point only if you have a C99 compiler (or
a C90 compiler that allows declarations to follow statements as an
extension) <OT>or a C++ compiler</OT>.

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #14
"ex******@gmail.com" <ex******@gmail.com> writes:
I am learning C, so I decided to try out r/w-ing to other files. Can
anyone please tell me why I get the following error when running the
program?
Transcript:
Name?
Nikhil R. Mulani
Bus error
Code:

#include <stdio.h>

main()
{
char name[60];
FILE *Fp;

Fp = fopen("/deeter.dat", "w");

printf("Name?\n");
scanf("%s",name);

fprintf(Fp, "Name: %s\n", name);

int fclose( FILE *Fp );
}


My best guess is that the fopen() call failed because you don't have
permission to create the named file. You then call fprintf() with Fp
as an argument, which invokes undefined behavior. Dropping the
leading '/' might address the problem. In any case, you need to check
whether the fopen() succeeded, and *don't* attempt to write to the
file if it failed.

Something else you should address is the fact that scanf("%s", name)
only grabs the first whitespace-delimited word of input; in this case,
just "Nikhil", not "Nikhil R. Mulani". You probably want fgets().

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #15
Jack Klein <ja*******@spamcop.net> wrote:
On 26 Feb 2005 17:59:11 GMT, Je***********@physik.fu-berlin.de wrote
in comp.lang.c:
5) The line

int fclose( FILE *Fp );

should get the compiler upset (and I strongly doubt that you got
the program compiled in the for you posted it). I guess you want
You went a little overboard here. The line represents a perfectly
correct prototype for the function fclose(), and a prototype is
perfectly legal at this point in the source code. So it most
certainly should compile, although it doesn't do what the OP expects.


Yes, thank you. I didn't realize that it's allowed now in C99 and
only tested in strict ANSI-89 mode.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #16
On Sat, 26 Feb 2005 20:23:56 GMT, Keith Thompson <ks***@mib.org> wrote
in comp.lang.c:
Jack Klein <ja*******@spamcop.net> writes:
On 26 Feb 2005 17:59:11 GMT, Je***********@physik.fu-berlin.de wrote
in comp.lang.c:

[snip]
5) The line

int fclose( FILE *Fp );

should get the compiler upset (and I strongly doubt that you got
the program compiled in the for you posted it). I guess you want


You went a little overboard here. The line represents a perfectly
correct prototype for the function fclose(), and a prototype is
perfectly legal at this point in the source code. So it most
certainly should compile, although it doesn't do what the OP expects.
fclose( Fp );

here - but don't call fclose() when 'Fp' is NULL.


The rest of your advice is excellent, of course.


A prototype is legal at that point only if you have a C99 compiler (or
a C90 compiler that allows declarations to follow statements as an
extension) <OT>or a C++ compiler</OT>.


You are correct, sir, my bad. Jens forgot about C99, and I forgot
about C90!

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #17

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

Similar topics

4
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be
5
by: Benjamin de Waal | last post by:
Hey all, I'm trying to figure out how to directly write to a device in Windows. Basically, what I'm wanting to do is create an image of a device (specifically, a CompactFlash card that uses a...
6
by: hpy_awad | last post by:
I am writing stings ((*cust).name),((*cust).address)to a file using fgets but rabish is being wrote to that file ? Look to my source please and help me finding the reason why this rabish is being...
24
by: ypjofficial | last post by:
Hello all, I have written a class with many private data members.and i am putting it in a separate dll file. Now when i link that file while writing my main program module,natuarally i have to...
15
by: leorulez | last post by:
Is there any way to read multiple files (more than 1000 files) and then write into one single output file using C? Right now in my program, I have a loop which asks for the filename and writes into...
6
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
7
by: random guy | last post by:
Hi, I'm writing a program which creates an index of text files. For each file it processes, the program records the start and end positions (as returned by tellg()) of sections of interest,...
3
by: Paul Moore | last post by:
I'd like to write some scripts to analyze and manipulate my music files. The files themselves are in MP3 and FLAC format (mostly MP3, but FLAC where I ripped original CDs and wanted a lossless...
0
Guido Geurs
by: Guido Geurs | last post by:
I'm writing a program that list the contents of a CDrom and also the contents of the ZIP files. When there is a bad Zip file on the CD, the program keeps traying to reed the file and after +- 50...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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...
0
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
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...
0
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
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,...

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.