Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have the following code
C++
#include<stdio.h>
void main()
  {
    FILE *f;
    char uname[20],pass[20],name1[]={"b"},pass1[]={"2"};
    int s=0,i=0;
    f=fopen("users.dat","r+");
    clrscr();
    do
    {
     s=(4*i);
     i++;
     fseek(f,s,SEEK_SET);
     fscanf(f,"%s %s",uname,pass);
     printf("\n%s %s",uname,pass);
     printf("\tcur pos : %ld",ftell(f));
     fflush(f);
    }while(!feof(f));
    getch();
  }

it is not working correctly
i want to read each line of a file "users.dat" but it is not giving the right answer

file users.dat has following contents

a 1
b 2
c 3
d 4
e 5
f 6
Posted

If your file strictly follows the format you posted (that is every line has 4 characters length) then your program should work as it stands.
On the other hand, if there are 'irregular' lines (for instance, having extra blanks) then your program would fail.
If you are going to allow such 'irregular' lines then you better use fgets[^] (instead of fseek) to read whole lines.
 
Share this answer
 
Here is the clue: the lines have different lengths. You don't know the lengths unless you read the file from the beginning to the end and somewhere remember file positions for each line. Only then you can use fseek to set position at certain line.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900