在c中使用fseek更改行 [英] changing the line using fseek in c

查看:170
本文介绍了在c中使用fseek更改行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

  #include   <   stdio.h  >  
< span class =code-keyword> void main()
{
FILE * f;
char uname [ 20 ],传递[ 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();
}



它无法正常工作

i想要读取文件users.dat的每一行,但它不是给出正确的答案



file users.dat有以下内容



a 1

b 2

c 3

d 4

e 5

f 6

解决方案

如果您的文件严格遵循您发布的格式(即每行都有 4 字符长度),那么您的程序应该按原样运行。

另一方面,如果有不规则的行(例如,有额外的空格),那么你的程序就会失败。

如果您打算允许这种不规则的行,那么最好使用 fgets [ ^ ](而不是 fseek )读取整行。


这是线索:线条长度不同。除非您从头到尾读取文件,并且某处记住每行的文件位置,否则您不知道长度。只有这样你才能用 fseek 来设定某一行的位置。



-SA

i have the following code

#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

解决方案

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.


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


这篇关于在c中使用fseek更改行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆