简体   繁体   English

用C解析文件(行)

[英]Parsing a file in C (Lines)

I have a file that looks like this: 我有一个看起来像这样的文件:

5
x=
6
y=

I want to initially skip the first line, parse the second line, then go back to the first line and strcat both strings. 我想首先跳过第一行,解析第二行,然后返回到第一行并strcat两个字符串。 However, I can't seem to get that working. 但是,我似乎无法正常工作。

For instance: 例如:

I have: 我有:

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

}

Note that my lines in my file are not always this simple, these are just example lines I'm trying to test out (Going back and fourth between lines, reading ahead etc). 请注意,文件中的行并不总是那么简单,它们只是我要测试的示例行(在各行之间来回移动,第四行,向前读取等)。

Any ideas? 有任何想法吗?

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

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

So if you know the offsets you can jump wherever you want. 因此,如果您知道偏移量,则可以随时随地跳转。

edit: 编辑:

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

Now if you want to loop that you need to save the offsets somewhere in order to jump back to them. 现在,如果要循环播放,则需要将偏移量保存在某处以便跳回到它们。 You can do this by using strlen() on the buffer ( char line[256] ) in my example and add the offsets up. 在我的示例中,可以通过在缓冲区( char line[256] )上使用strlen()并添加偏移量来实现此目的。

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

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