Using fgets() in file parsing

2019-07-23 14:13发布

I have a file which contains several lines.

I am tokenizing the file, and if the token contains contains .word, I would like to store the rest of the line in c-string.

So if: array: .word 0:10 I would like to store 0:10 in a c-string.

I am doing the following:

if (strstr(token, ".word")) {
    char data_line[MAX_LINE_LENGTH + 1];
    int word_ret = fgets(data_line, MAX_LINE_LENGTH, fptr);
    printf(".word is %s\n", data_line);
}

The problem with this is that fgets() grabs the next line. How would I grab the remainder of the current line? Is that possible?

Thank you,

3条回答
姐就是有狂的资本
2楼-- · 2019-07-23 14:31

First of all it is obvious that you need to use fgets only once for every line you parse and then work with a buffer where the line is stored.

Next having a whole line you have several choices: if the string format is fixed (something like " .word") then you may use the result of "strstr" function to locate the start of ".word", advance 6 characters (including space) from it and print the required word from the found position.

Another option is more complex but in fact is a liitle bit better. It is using "strtok" function.

查看更多
我命由我不由天
3楼-- · 2019-07-23 14:34

strstr() returns a pointer to where the first character of ":word" is found.

This means that if you add the length of ":word" (5 characters) to that, you will get a pointer to the characters after ":word", which is the string you want.

char *x = strstr(token, ".word");
char *string_wanted = x + 5;
查看更多
一夜七次
4楼-- · 2019-07-23 14:50

You need to have already read the input into a buffer, which I'm assuming is token, and from there you just copy from the return value of strstr + the length of ".word" to the end of the buffer. This is what I'd do:

char *location = strstr(token, ".word");
if (location != NULL) {
   char data_line[MAX_LINE_LENGTH];
   strncpy(data_line, location + 5, MAX_LINE_LENGTH);
   printf(".word is %s\n", data_line);
}

You could add 5 or 6 to the pointer location (depending on whether or not there's going to be a space after ".word") to get the rest of the line.

Also note that the size parameter in strncpy and fgets includes space for the terminating NUL character.

查看更多
登录 后发表回答