I've a problem with file handling program: see this

R

Rajen

When I run this program:
#include<stdio.h>

int main()
{
FILE *fp;

int i;
float f;
char str[20];

if( ( fp=fopen("stuff", "w")) == NULL )
{
printf("Sorry! Unable to create/read stuff");
exit(-1);
}

for( i=0; i<=10; i++ )
fprintf(fp, "%d:%s:%.2f\n", i, "Hello", 12.3f);

for( i=0; i<=5; i++)
{
fscanf( fp, "%d:%s:%.2f\n" , &i, &str, &f);
printf("Hi %s %d %f\n", str, i, f);
}

fclose(fp);
return 0;
}

This is the output.
$./a.out
Hi |àÇù¿-F¦Yâ 0 0.000000
Hi |àÇù¿-F¦Yâ 1 0.000000
Hi |àÇù¿-F¦Yâ 2 0.000000
Hi |àÇù¿-F¦Yâ 3 0.000000
Hi |àÇù¿-F¦Yâ 4 0.000000
Hi |àÇù¿-F¦Yâ 5 0.000000

The content of the file:
$cat stuff
0:Hello:12.30
1:Hello:12.30
2:Hello:12.30
3:Hello:12.30
4:Hello:12.30
5:Hello:12.30
6:Hello:12.30
7:Hello:12.30
8:Hello:12.30
9:Hello:12.30
10:Hello:12.30

why is this while I read string and float values. Help me where I'm
wrong.
Thanks in advance
 
A

Amitabha Roy

First, you should open the file in read write mode, not just write

if( ( fp=fopen("stuff", "w+")) == NULL )
....

You should rewind the file before attempting to read from it after you finish writing:
> for( i=0; i<=10; i++ )
> fprintf(fp, "%d:%s:%.2f\n", i, "Hello", 12.3f);
rewind(fp);

Last your format specifiers are all wrong wrt your intent. How is the
%s in the fscanf going to figure out where the string is ending ?
I guess you can fix that yourself.

-Amitabha



When I run this program:
#include<stdio.h>

int main()
{
FILE *fp;

int i;
float f;
char str[20];

if( ( fp=fopen("stuff", "w")) == NULL )
{
printf("Sorry! Unable to create/read stuff");
exit(-1);
}

for( i=0; i<=10; i++ )
fprintf(fp, "%d:%s:%.2f\n", i, "Hello", 12.3f);

for( i=0; i<=5; i++)
{
fscanf( fp, "%d:%s:%.2f\n" , &i, &str, &f);
printf("Hi %s %d %f\n", str, i, f);
}

fclose(fp);
return 0;
}

This is the output.
$./a.out
Hi |àÇù¿-F¦Yâ 0 0.000000
Hi |àÇù¿-F¦Yâ 1 0.000000
Hi |àÇù¿-F¦Yâ 2 0.000000
Hi |àÇù¿-F¦Yâ 3 0.000000
Hi |àÇù¿-F¦Yâ 4 0.000000
Hi |àÇù¿-F¦Yâ 5 0.000000

The content of the file:
$cat stuff
0:Hello:12.30
1:Hello:12.30
2:Hello:12.30
3:Hello:12.30
4:Hello:12.30
5:Hello:12.30
6:Hello:12.30
7:Hello:12.30
8:Hello:12.30
9:Hello:12.30
10:Hello:12.30

why is this while I read string and float values. Help me where I'm
wrong.
Thanks in advance
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top