繁体   English   中英

用C解析文件(行)

[英]Parsing a file in C (Lines)

我有一个看起来像这样的文件:

5
x=
6
y=

我想首先跳过第一行,解析第二行,然后返回到第一行并strcat两个字符串。 但是,我似乎无法正常工作。

例如:

我有:

while(fgets(buffer,sizeof(buffer),file) != NULL) {

     fgets(buffer,100,file); //skip first line

     char * tempVar = malloc(sizeof(char)*10);

     strcpy(tempVar,buffer); //copy second line into tempVar

     rewind(file); //go back to first line? doesnt work

     //then strcat the two strings, so I get x=5

}

请注意,文件中的行并不总是那么简单,它们只是我要测试的示例行(在各行之间来回移动,第四行,向前读取等)。

有任何想法吗?

您可以使用int fseek ( FILE * stream, long int offset, int origin ); int origin可以在哪里

SEEK_SET    Beginning of file
SEEK_CUR    Current position of the file pointer
SEEK_END    End of file *

因此,如果您知道偏移量,则可以随时随地跳转。

编辑:

FILE* file = fopen(fileName, "r"); 
char line[256];

fgets(line, sizeof(line), file); //skip first
fgets(line, sizeof(line), file);
printf("%s", line);  //  prints x=
fseek ( file , 0 , SEEK_SET );
fgets(line, sizeof(line), file); 
printf("%s", line);  // prints 5

现在,如果要循环播放,则需要将偏移量保存在某处以便跳回到它们。 在我的示例中,可以通过在缓冲区( char line[256] )上使用strlen()并添加偏移量来实现此目的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM