Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Silly question on fread 1

Status
Not open for further replies.

SmileeTiger

Programmer
Mar 13, 2000
200
US
I have a silly question.. I can't figure out why the following gives me an error.

int i_NumNumbers;
char c_Num[255];// take the data as a character since it is going to be dumped into a .txt file
int i; //Loop var's

FILE *File;
File=fopen("INPUTDATA.txt", "wt");

do
{
printf("Please enter the number of numbers which you intend to perform operations on");
scanf("%i",&i_NumNumbers);

} while(i_NumNumbers <= 1);

for (i=0; i<i_NumNumbers; i++)
{
printf(&quot;\nWhat is #%i?&quot;,i );
scanf(&quot; %s&quot;, &c_Num); //It's a string 'cause I want to handle
//Floats
printf(&quot;The number is: %s\n&quot;,c_Num);
fwrite(c_Num, sizeof(char) ,255, File);
fwrite(&quot;,&quot;, sizeof(&quot;,&quot;), 1, File);

}
fclose(File);


I keep getting junk as the output of this code.. can anyone spot my error?

I think it is due to the fact that fread is spitting out all the elements in the string to the text file.. perhaps I have to add a null on the end of the string.. is there any easy way to do this?

Smilee
 
Try changing the line

File=fopen(&quot;INPUTDATA.txt&quot;, &quot;wt&quot;);

to

if ((File=fopen(&quot;INPUTDATA.txt&quot;, &quot;wt&quot;))==NUL)
{gotoxy(20,10);
clreol();
cprintf(&quot;ERROR OPENING INPUT FILE&quot;);
}

keep the name of the input file as 8 + 3 characters
 
Remove the & before the c_Num in the scanf(...);

I think you are seeing the file INPUTDATA.txt for the result (by opening it through any editor).

The fwrite function will write given number of bytes into the file(what ever may be the characters within it).

In your case you may have few characters (like 321) in the c_Num array but the fwrite will write 255 characters from the array to the file. So the remaining garbage from from the array will be stored. That is why you are getting the garbage characters within our INPUTDAT.txt.

Use the binary mode for fread/fwrite options because in text mode character promotion will occur in text mode.
There is no need to write (in your case ,)separaters between the data because you will read the data from the file based on the size.

If you just want to see the result within the text file as like as the output window the use fprintf(...);

you can put fprintf(File, &quot;%s,&quot;, c_Num);

Maniraja S
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top