Thread: Help Reading File Line By Line On Windows?

  1. #1
    Registered User
    Join Date
    Oct 2014
    Posts
    6

    Help Reading File Line By Line On Windows?

    Hello everybody,

    I was just wondering if someone could give me example code on how to read a file line by line and then later access them by doing something like

    Code:
    lines[0] //Line number one
    ...
    lines[100] //Line number one hundred and one
    lines[100][0] //L
    lines[100][1] //i
    lines[100][2] //n
    lines[100][3] //e
    lines[100][4] // 
    lines[100][5] //n
    ...
    I've been trying to figure this out for a long time and still just can't get this.

    Anyone who can help you'd be greatly appreciated!
    Last edited by new2c95; 10-13-2014 at 08:52 AM.

  2. #2
    Registered User
    Join Date
    Nov 2011
    Posts
    161
    What's your code so far?
    And what kind of file, source code or text file?

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    You can use fgets to read a file line by line. Example usage is like this

    Code:
    char line[100];
    while (fgets(line, 100, fp)) {
    	// do something with line
    }
    In the loop you do whatever you need to with the line, such as print it out, process it, etc. You could also strcpy them into an array like in your example if you want.

  4. #4
    Registered User
    Join Date
    Oct 2014
    Posts
    6
    Quote Originally Posted by FloridaJo View Post
    What's your code so far?
    And what kind of file, source code or text file?
    I've got some argument checking above the code I'm posting so this is just the main snippet

    Code:
    FILE *fp;
    char *ch;
    ....
            if ((fp = fopen(argv[1], "rb")) != 0)
            {
                printf("[+] %s opened\n", argv[1]);
                
                while ((fread(ch, 1, 1, fp)) == 1)
                {
                    printf("\n%s\n", ch);
    For testing I'm just using the main C source file.

  5. #5
    Registered User
    Join Date
    Oct 2014
    Posts
    6
    Quote Originally Posted by c99tutorial View Post
    You can use fgets to read a file line by line. Example usage is like this

    Code:
    char line[100];
    while (fgets(line, 100, fp)) {
        // do something with line
    }
    In the loop you do whatever you need to with the line, such as print it out, process it, etc. You could also strcpy them into an array like in your example if you want.
    What if the file is a binary file or the line is longer than 100 characters? Will that still work?

  6. #6
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by new2c95 View Post
    What if the file is a binary file or the line is longer than 100 characters? Will that still work?
    Opening in binary basically just means that newline conversion will not be done. So e.g. if you read a Windows-style text file in binary mode, the IO library will put exactly the two characters in the buffer that represent a newline for Windows text files.

    If the line you read does not fit into the buffer, then it will take multiple iterations through the loop to read it.

    The best way is to try it out with a text file with long lines. Try to open in both text and binary modes and observe how long you must make your buffer.

  7. #7
    Registered User
    Join Date
    Oct 2014
    Posts
    6
    Quote Originally Posted by c99tutorial View Post
    Opening in binary basically just means that newline conversion will not be done. So e.g. if you read a Windows-style text file in binary mode, the IO library will put exactly the two characters in the buffer that represent a newline for Windows text files. If the line you read does not fit into the buffer, then it will take multiple iterations through the loop to read it. The best way is to try it out with a text file with long lines. Try to open in both text and binary modes and observe how long you must make your buffer.
    But every file will have a different line size. Isn't there some way I could detect the line size?

  8. #8
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by new2c95 View Post
    Isn't there some way I could detect the line size?
    You have to read the line to the end to determine how long it is. You could also use dynamic allocation so that you increase the size of your buffer by 100 (for example) each time it fills up. Another popular strategy is to double the size of the buffer when it fills up, and to repeat this process until you get the entire line (or until your hit an out of memory error). Look for dynamic allocation tutorials to learn about these techniques. However for normal text files allocating a fixed buffer works just fine as long as you make it large enough.

  9. #9
    Registered User
    Join Date
    Oct 2014
    Posts
    6
    Is anyone able to give me a code example?

  10. #10
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    An example for what? Using fgets with a buffer is simple, as I mentioned. For dynamic allocation, a more sophisticated approach is needed. See here for an example implementatio of that approach: http://www8.cs.umu.se/~isak/snippets/getstrng.c

  11. #11
    Registered User
    Join Date
    Jun 2014
    Posts
    79
    Provided that you don't have to load a file with a size in the order of some GB's, I suggest that you try something like this:


    1. check the size of the file
    2. allocate a chunk of dynamic memory as large as needed to contain the whole contents of the file
    3. load the contents of the file in the allocated memory
    4. scan the resulting string in order to count the total number of '\n' characters contained in the allocated memory (which equal to the number of lines)
    5. allocate a chunk of memory containing space for a vector of pointers to char as long as the number of lines
    6. store the pointer to the first character of the loaded string, then scan the loaded string again looking for each '\n' character; whenever you do find one, do two things: a. put a '\0' terminator in place of the '\n' and b. store the index of the next character into the next pointer to char of your vector


    When the process is done, you should have a vector containing pointers to char, each of which pointing to the very start of one line taken from the file and zero terminated. You then should be able to access those strings by using the pointers stored in the vector with simple zero-based indexes.

    Of course, it would be a good thing isolating the mechanism I just described in a dedicated subroutine.

    I could provide sample code, and you surely could grasp the mechanism in a much easier way, but looks like providing complete sample code is forbidden in this forum.

  12. #12
    Registered User
    Join Date
    Oct 2014
    Posts
    6
    Quote Originally Posted by aldo_baldo View Post
    Provided that you don't have to load a file with a size in the order of some GB's, I suggest that you try something like this:
    1. check the size of the file
    2. allocate a chunk of dynamic memory as large as needed to contain the whole contents of the file
    3. load the contents of the file in the allocated memory
    4. scan the resulting string in order to count the total number of '\n' characters contained in the allocated memory (which equal to the number of lines)
    5. allocate a chunk of memory containing space for a vector of pointers to char as long as the number of lines
    6. store the pointer to the first character of the loaded string, then scan the loaded string again looking for each '\n' character; whenever you do find one, do two things: a. put a '\0' terminator in place of the '\n' and b. store the index of the next character into the next pointer to char of your vector

    When the process is done, you should have a vector containing pointers to char, each of which pointing to the very start of one line taken from the file and zero terminated. You then should be able to access those strings by using the pointers stored in the vector with simple zero-based indexes. Of course, it would be a good thing isolating the mechanism I just described in a dedicated subroutine. I could provide sample code, and you surely could grasp the mechanism in a much easier way, but looks like providing complete sample code is forbidden in this forum.
    Any possible way you get me the source somehow?

  13. #13
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by new2c95 View Post
    Any possible way you get me the source somehow?
    Are you looking for someone to solve your specific problem for you and post source code to that solution? The purpose of this forum is to learn and get suggestions, improve your skills. If you post what you've got so far as a complete program maybe someone can suggest the next step or help you fix what is broken.

  14. #14
    Registered User
    Join Date
    Jun 2014
    Posts
    79
    Quote Originally Posted by new2c95 View Post
    Any possible way you get me the source somehow?
    I have the code in the form of a LoadStrings() function, and I really WOULD LIKE to share it with you. I'm just an enthusiastic self-taught, low-end hobbyist, and I know very well that one can learn a lot by looking at someone else's code (I learnt so much that way). I can't understand how giving examples could make any harm, but I don't want to break the rules of the forum.

    Someone here can explain me what's the difference between providing tutorials and providing some sample code? There are tutorials, here, so why can't we share sample code?
    Last edited by aldo_baldo; 10-14-2014 at 09:41 AM. Reason: Typos correction

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems while reading a file line by line
    By tinchi in forum C Programming
    Replies: 9
    Last Post: 08-17-2014, 12:10 PM
  2. Replies: 6
    Last Post: 06-07-2012, 02:50 AM
  3. Replies: 7
    Last Post: 12-13-2010, 02:13 PM
  4. reading words line by line from a file
    By -EquinoX- in forum C Programming
    Replies: 3
    Last Post: 05-04-2008, 12:34 AM
  5. reading a file line by line and char *
    By odysseus.lost in forum C Programming
    Replies: 8
    Last Post: 05-31-2005, 09:47 AM

Tags for this Thread