Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File Reading

Status
Not open for further replies.

euacela1

Programmer
Apr 12, 2004
3
RO
Can someone tell me please hoe can I read from a file from a certain line. How can I make the cursor that reads to a certain line?
The only fumtion I know is fscanf() and the only one that seeks if fseek() but fseek is a function that jump over kb-s And I need something to take me to a certain line.
Tahnk you.


 
A for loop and fgets() is the only easy way to get to a specific line within a file.

If you're doing this a lot (and the text file is fairly static), then you can build an index, which will allow you to fseek() to a line of your choice.

--
 
If you don't mind using the Win32 API (CreateFile, ReadFile, etc.) for files rather than the runtime library (fopen, fread, etc.), here is another way to search for a specific line in a file. First, map the file into memory using MapViewOfFile. Then, in a loop, scan the mapped memory, counting the number of newline characters (ASCII code 0x0A). When the count reaches the desired line number minus one, stop scanning the file.

Here is an example (not tested and does not handle exceptional conditions):

Code:
HANDLE in = CreateFile ("myfile.txt", GENERIC_READ, FILE_SHARE_READ,
                        NULL, OPEN_EXISTING,
                        FILE_ATTRIBUTE_NORMAL, NULL);
const unsigned long inSize = GetFileSize (in, NULL);
HANDLE inMapping = CreateFileMapping
    (in, NULL, PAGE_READONLY, 0, 0, NULL);
const char *inData = reinterpret_cast<const char *>
    (MapViewOfFile (inMapping, FILE_MAP_READ, 0, 0, 0));

unsigned long lineCount = 0;
unsigned long i;
for (i = 0; i < inSize; ++i)
{
    if (lineCount == desiredLineNumber) break;
    if (inData [i] == '\n') ++lineCount;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top