Click here to Skip to main content
Rate this: bad
Please Sign up or sign in to vote.
See more: C++ C
I have a text file . in this file there are 3 text liens .
I want to read the text file .
How can I read line by line this file ?
Posted 21-Sep-12 21:15pm
Edited 21-Sep-12 21:16pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

You could use the C library fread()[^] function, or the C++ iostream[^] class.
pasztorpisti at 22-Sep-12 9:15am
+5, iostream can also be used if someone isnt allergic to its syntax.
Richard MacCutchan at 22-Sep-12 10:04am
It usually takes me an hour or two to figure it out.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

If you want to keep it simple stupid:
#include <stdio.h>

void process_line(const char* line)
    // you line processing here
void test()
    FILE* f = fopen("myfile.txt", "r");
    if (f)
        // replace the line below to "for (;;)" if you want to process all lines
        for (int i=0; i<3; ++i)
            const int MAX_LINE_LENGTH = 0x100;
            char line[MAX_LINE_LENGTH];
            if (!fgets(line, sizeof(line), f))
            int len = strlen(line);
            if (len>0 && line[len-1]=='\n')
                line[len-1] = 0;
Richard MacCutchan at 22-Sep-12 8:56am
Here's the +5 I owe you :)
pasztorpisti at 22-Sep-12 9:10am
Thank you, its even one more than needed. I will remember it! :-)
Richard MacCutchan at 22-Sep-12 9:14am
It was in response to your comment about "How to inject a DLL into a .exe".
pasztorpisti at 22-Sep-12 9:16am
Got it! ;-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 339
1 Nirav Prabtani 248
2 OriginalGriff 234
3 _Amy 165
4 Maciej Los 145
0 OriginalGriff 7,744
1 Sergey Alexandrovich Kryukov 6,956
2 Maciej Los 3,994
3 Peter Leow 3,708
4 CHill60 2,742

Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 22 Sep 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100