473,725 Members | 2,050 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

beginner level question

hi all,
I trying to write an array of integers into a text
file.While writing into the file it works.I used fwrite function, but
when I read the same file using fread or fscanf it fails and it prints
some junk.I am not opening the file in binary mode, there are no
characters which will terminate the fscanf function operation.How to
write and read the integer array .
Thanks in advance.

Jul 17 '06 #1
9 1531

raam wrote:
hi all,
I trying to write an array of integers into a text
file.While writing into the file it works.I used fwrite function, but
when I read the same file using fread or fscanf it fails and it prints
some junk.I am not opening the file in binary mode, there are no
characters which will terminate the fscanf function operation.How to
write and read the integer array .
Thanks in advance.
a small addition to the above.
I am using DOS, Turbo c 2.0. in a win98 machine.

Jul 17 '06 #2
raam wrote:
hi all,
I trying to write an array of integers into a text
file.While writing into the file it works.I used fwrite function, but
when I read the same file using fread or fscanf it fails and it prints
some junk.I am not opening the file in binary mode, there are no
characters which will terminate the fscanf function operation.How to
write and read the integer array .
Thanks in advance.
If you do not require the file to be binary, it might be easier for you
to write the file with fprintf and read it back with fscanf. Then you
will be able to check the data is written correctly by reading the file.

If you write binary data with fwrite, you should read it back with
fread, not fscanf. If you write a binary file, you should open it in
binary mode, otherwise characters such as line feed and null will be
misinterpreted.

For more help, post the code you are having problems with.

--
Ian Collins.
Jul 17 '06 #3
raam wrote:
hi all,
I trying to write an array of integers into a text
file.While writing into the file it works.I used fwrite function, but
when I read the same file using fread or fscanf it fails and it prints
some junk.I am not opening the file in binary mode, there are no
characters which will terminate the fscanf function operation.How to
write and read the integer array .
Your problem is almost certainly on line 42.

Of course, we can give you a more accurate assessment and instruction
if you post the code that you're actually working on.

P.S. Have a look at...

http://clc-wiki.net/wiki/C_community...c:Introduction

--
Peter

Jul 17 '06 #4
hi all,
thanks for the reply.
This is the code
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

main(){
FILE *p;
struct mm{
int a[100];
};
struct mm *n;
int i;
n = (struct mm *)malloc(sizeof (struct mm));
printf( "\n Press any key ");
getch();
for(i = 0 ; i<100 ; i++)
n->a[i]= i;
p = fopen("example. txt","w");
for(i = 65;i<75;i++)
printf("%d, ",n->a[i]);
getch();
fwrite(n,sizeof (struct mm),1,p);
fclose(p);

for(i = 0 ; i<100 ; i++)
n->a[i]= 0;
p = fopen("example. txt","r");
fread(n,sizeof( struct mm),1,p);
fclose(p);

p = fopen("example1 .txt","w");
fwrite(n,sizeof (struct mm),1,p);
fclose(p);

for(i = 65;i<75;i++)
printf("%d, ",n->a[i]);

printf( "\n Press any key ");
getch();
free(n);
exit(0);
}

Jul 17 '06 #5
On 17 Jul 2006 00:23:54 -0700, "raam" <mu************ ***@gmail.com>
wrote:
hi all,
thanks for the reply.
This is the code
#include <stdio.h>
#include <conio.h>
A non-standard header may of us don't have and which you don't need.
>#include <stdlib.h>

main(){
int main(void)
>FILE *p;
struct mm{
int a[100];
};
struct mm *n;
int i;
n = (struct mm *)malloc(sizeof (struct mm));
Don't cast the return from malloc. It can never help and will allow
the compiler to suppress a diagnostic you would really want to see.

You should check calls to malloc for success.
> printf( "\n Press any key ");
getch();
A non-standard function many of us don't have. If you change the
message to refer to the ENTER key, you could use the standard
getchar() function.
> for(i = 0 ; i<100 ; i++)
n->a[i]= i;
p = fopen("example. txt","w");
You should check calls to fopen for success.
> for(i = 65;i<75;i++)
printf("%d, ",n->a[i]);
getch();
How is the user supposed to know it is time to press a key to
continue?
> fwrite(n,sizeof (struct mm),1,p);
This writes the binary structure to a file in text mode. Certain byte
values may special meaning to your operating system and be altered as
they are sent to the output device.
> fclose(p);

for(i = 0 ; i<100 ; i++)
n->a[i]= 0;
p = fopen("example. txt","r");
fread(n,sizeof( struct mm),1,p);
This attempts to read the binary structure from a file in text mode.
Certain byte values may special meaning to your operating system and
be altered as they are received from the output device or they may
cause the input operation to terminate.

You should definitely check calls to fread for success.
> fclose(p);

p = fopen("example1 .txt","w");
fwrite(n,sizeof (struct mm),1,p);
fclose(p);

for(i = 65;i<75;i++)
printf("%d, ",n->a[i]);

printf( "\n Press any key ");
getch();
free(n);
exit(0);
}
You may have better success if you change all your calls to fopen to
specify binary mode instead of text mode.

It's not related to your problem but you don't need to enclose the
array in a structure.
Remove del for email
Jul 17 '06 #6

raam wrote:
hi all,
thanks for the reply.
This is the code
#include <stdio.h>
#include <conio.h>
Be aware that this header is specific to the Microsoft platform, and is
not available everywhere.
#include <stdlib.h>

main(){
This line should be written as

int main(void) {

First of all, implicit typing (assuming a function returns int unless
otherwise specified) is a reliable source of errors, and second of all,
it's no longer supported in the latest version of the C standard.
FILE *p;
struct mm{
int a[100];
};
struct mm *n;
int i;
n = (struct mm *)malloc(sizeof (struct mm));
Unless you are working with a *very* old implementation (pre-C89),
don't cast the result of malloc().

First of all, malloc() returns a void*, which can be implicitly
converted to any other object pointer type. Second of all, if you
forget to #include <stdlib.hor otherwise not have a prototype for
malloc() in scope, casting the result will prevent the compiler from
issuing a diagnostic, and you may experience some weird problems at
runtime.

Rewrite that line as

n = malloc(sizeof *n);

"sizeof *n" is synonymous with "sizeof(str uct mm)", which is a little
easier to read, and if you ever change the type of n, you don't have to
make the corresponding change to the malloc() call.

*ALWAYS* check the result of malloc() before trying to use it.
printf( "\n Press any key ");
getch();
Again, be aware that any functions from the conio library are specific
to the Microsoft platform, and will not be universally available.
for(i = 0 ; i<100 ; i++)
n->a[i]= i;
p = fopen("example. txt","w");
Since you're using fread() and fwrite(), you'll want to open the file
in binary mode, like so:

p = fopen("example. txt", "wb");

BTW, it's *always* a good idea to check that the return value of
fopen() isn't NULL, just in case the file could not be created.
for(i = 65;i<75;i++)
printf("%d, ",n->a[i]);
In order to guarantee that the text shows up on the screen, either
print a newline or call fflush(stdout) at this point.
getch();
fwrite(n,sizeof (struct mm),1,p);
Again, you can replace sizeof(struct mm) with sizeof *n.
fclose(p);

for(i = 0 ; i<100 ; i++)
n->a[i]= 0;
p = fopen("example. txt","r");
Same thing as above; replace "r" with "rb", and make sure to check the
result isn't NULL before continuing.
fread(n,sizeof( struct mm),1,p);
fclose(p);

p = fopen("example1 .txt","w");
fwrite(n,sizeof (struct mm),1,p);
fclose(p);

for(i = 65;i<75;i++)
printf("%d, ",n->a[i]);

printf( "\n Press any key ");
getch();
free(n);
exit(0);
}
Jul 17 '06 #7
Barry Schwarz <sc******@doezl .netwrites:
On 17 Jul 2006 00:23:54 -0700, "raam" <mu************ ***@gmail.com>
wrote:
[...]
>> printf( "\n Press any key ");
getch();

A non-standard function many of us don't have. If you change the
message to refer to the ENTER key, you could use the standard
getchar() function.
I think you're suggesting something like this:

printf("\n Press ENTER ");
fflush(stdout); /* I added this */
getchar(); /* ignore result */

The problem with this is that if the user types "foobar<ENT ER>" rather
than just "<ENTER>", the call to getchar() will return 'f' and leave
the characters "oobar\n" in the input stream, to be read by further
input calls.

Here's a function the OP might find useful:

void skip_line(void)
{
int c;
while ((c = getchar()) != '\n' && c != EOF) {
/* do nothing */
}
}

--
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.
Jul 17 '06 #8
hi all,
I changed the extension from .txt to .dat and used only "wb"
and "rb" modes and now the program is working .I thought , whatever we
write the OS will dump it into the file but it seems that is not the
case and it depends on the file type.
Thanks for all your help.
Raam.

Jul 18 '06 #9
raam wrote:
hi all,
I changed the extension from .txt to .dat and used only "wb"
and "rb" modes and now the program is working .I thought , whatever we
write the OS will dump it into the file but it seems that is not the
case and it depends on the file type.
It is the "rb" and "wb" that fixed your problem. Changing the extension
from ".txt" to ".dat" is a good idea, but it would not change what is
written to the file.

--
Simon.
Jul 18 '06 #10

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

Similar topics

5
3077
by: Richard B. Kreckel | last post by:
Hi! I was recently asked what book to recommend for a beginner in C++. I am convinced that you needn't study C in depth before learning C++ (though it helps), but cannot find any beginner's book which isn't aimed at people coming from C/Pascal/Java/Delpi/whatever... However, there seem to be plenty such books for all those other languages. Is there really no literature for people trying to learn programming by starting with C++? ...
44
4251
by: lester | last post by:
a pre-beginner's question: what is the pros and cons of .net, compared to ++ I am wondering what can I get if I continue to learn C# after I have learned C --> C++ --> C# ?? I think there must be many know the answer here. thanks
16
2620
by: dario | last post by:
Hi, Im new on phyton programming. On my GPRS modem with embedded Phyton 1.5.2+ version, I have to receive a string from serial port and after send this one enclosed in an e-mail. All OK if the string is directly generated in the code. But it doesn't works if I wait for this inside a 'while' loop. This is the simple code: global stringZVEI
12
1888
by: Blaze | last post by:
I am doing the first walk through on the Visual Studio .Net walkthrough book to learn a little about programming. I am having issues with the first tutorial not running correctly. It seems that the build fails with what the book tells me to do. Specifically, I am doing this: public authors1 GetAuthors() { authors1 authors = new Authors1();
6
1569
by: Alex | last post by:
Hello I am intersting in developing and my background is VBA used in Excel and a brief intro to Java. I am interested in learning beyond VB and feel that C++ would be a very good language to get to know and give a lot of flexibility (if not tough to learn). I would like some advice on the merits of learning C++ versus C# or Visual Basic or Java for that matter.
4
1669
by: Yoram Biberman | last post by:
I have a few questions concerning concurrency control. I shall thank whoever can help me. Question #1 ========= Assume the following (concurrent) schedule, in which both transactions run in a serializable isolation level: T1 begin T2 begin T1 modifies an item A
18
2920
by: mitchellpal | last post by:
Hi guys, am learning c as a beginner language and am finding it rough especially with pointers and data files. What do you think, am i being too pessimistic or thats how it happens for a beginner? Are there better languages than c for a beginner? For instance visual basic or i should just keep the confidence of improving?
15
2317
by: Notre Poubelle | last post by:
Hello, I have a large legacy MFC application. As is typical, there is an executable along with several MFC DLLs. One of these DLLs is created by staticly linking in many libraries resulting in one very large DLL that has the bulk of the code. I've downloaded the MFCWinFormsSample.EXE and have noticed that the main app could stay as a native executable (i.e. no CLR support) whereas the various ..DLLs can be marked as having CLR...
8
2324
by: AG | last post by:
Hello, This is my first post to this group, and on top of that I am a beginner. So please direct me to another group if this post seems out of place.... I have recently written a program which calculates loan amortization schedules, writes the data to a text file, and then upon user prompt, the program will display the created file and print the file. Until this morning, everything worked fine, and then I started messing around with...
8
1155
by: eggie5 | last post by:
I keep getting an error for line 7, what's wrong with this? from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question
0
8886
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9168
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
9104
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
8090
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6701
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6010
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
4509
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...
1
3217
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
3
2154
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.