开发者

C++ file operations : Reading specific line in a file. [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I want to make a program, that can read a file from a certain point in the file. For example, if I had a file with this text:

1:
Hel开发者_如何转开发lo world. THis is the first string

2:
Hello. This is the second string

3:
Hi!

So, now that I have to file, how can I make the program only read the second string?


For a text file that is dynamic in nature, you are going to have to getline() in a loop from the beginning. If it doesn't change super often, you could record the absolute file position and then check the file modification date to decide whether to do a direct seek in the case it hasn't been modified since the last looping getline(), or have to loop again. There's no magic in the file I/O routines that memorizes where each string ends in a file.


I will not write any code for you, and will just tell the way I would have done it.
Assumptions:
The format in which the strings start, e.g 1:, 2: etc. doesn't appear in the contents of a string.

Method:

  1. Start from the beginning of the file, and do seekg() and increment the get pointer each time, unless you find the 2 characters you are looking at e.g "2:" together.
    Stop there, start fetching your contents, until you find the next 2 characters of the form "number:" e.g "3:".

  2. If the file format that you have described is that way, you can use getline(), to fetch each line. This way you won't have to move the pointers for each character, but this works only if the data in the file is in a certain format.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜