Thread: Is there any way to read a line from a text file?

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    10

    Is there any way to read a line from a text file?

    Hi, that's the question. Is there any way to read a line from a text file (I want it to work with .srt files). I want to read a line and just a line, but the problem is that I don't know how to detect when a line finishes and a line starts.

    Thanks in advance.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    If you use fgets() to read the line, it will do the work of splitting the lines for you.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    The line finishes with '\n', the newline character. The next line starts after the '\n'. In windows I believe the lines are ended with '\r' '\n', 2 special characters.
    The file is ended with EOF, which an int.
    So this:
    aaaaaaaaaaaa
    bbbbbbb
    cccccccccccccc

    is stored like this:
    aaaaaaaaaaaa\nbbbbbbb\ncccccccccccccc\nEOF
    or in text in windows maybe like this:
    aaaaaaaaaaaa\r\nbbbbbbb\r\ncccccccccccccc\r\nEOF

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Note that unless you specifically ask to open the file in binary mode, reading from a file that has "\r\n" in it will give you a single "\n" in the input.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    I use something like this, seems to work for a lot of files for me.
    I'm not saying it's the best method but it does a job for me.
    Basically reads everythng up to a \n and then the \n is read too to get you
    ready for the next line.

    Code:
    	if (	(ptr2=fopen("hands2.doc","r")) == NULL) {
    		puts("file2 does not exist");
    		exit(2);	/* an early file does not exist	*/
    	}
    	do{ 
    		filelist=fscanf(ptr2,"%[^\n]\n",linebuffer);   
    		if (filelist==-1) break;
             }while(1)

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by esbo View Post
    I use something like this, seems to work for a lot of files for me.
    I'm not saying it's the best method but it does a job for me.
    Basically reads everythng up to a \n and then the \n is read too to get you
    ready for the next line.

    Code:
    	if (	(ptr2=fopen("hands2.doc","r")) == NULL) {
    		puts("file2 does not exist");
    		exit(2);	/* an early file does not exist	*/
    	}
    	do{ 
    		filelist=fscanf(ptr2,"%[^\n]\n",linebuffer);   
    		if (filelist==EOF) break;
             }while(1)
    Do not assume that EOF is -1 when there is a symbol for it - yes, it is almost certain to be -1, but what happens if it ISN'T on the original posters system?

    Also, fscanf() is not good for reading strings this way, since it's quite possible to overflow the buffer.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Registered User
    Join Date
    Jan 2009
    Posts
    10
    Thanks for the answers. Here is what I've got so far:

    Code:
    #include <stdio.h>
    
    main()
    {
       FILE *archivo;
       int linea = 1, i, num = 0;
       char ubicacion[60], linea2[40], *ptr, caracter;
    
       printf("ubication of the file: ");
       scanf("%s", ubicacion);
       if ((archivo = fopen(ubicacion, "r")) == NULL)
          printf("File could not be opened\n");
       else {
          while (1) {
             for (i = 1; i <= 4 && (fgetc(archivo) != EOF); i++) {
                if (i == 2) {
    		  caracter=fscanf(archivo,"%[^\n]\n",linea2); 
                      printf("%s\n", linea2);
                }
             }
          }
    
       }
    
       return 0;
    }
    But it doesn't work! As you can see, what it should do is print the second line, counting until the line 4, to start all over again and so forth. But it seems to print random line, not just the second line. I'm completely clueless about what's the problem. Oh, one more thing, I think I mentioned that I'm working with .srt files. I don't know if that affects the result so I think it's worth to mention.

    Thanks for all of your answers.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > But it doesn't work!
    Not entirely surprising given that you swallowed esbo's poison.

    Code:
    char buff[BUFSIZ];
    while ( fgets( buff, sizeof buff, archivo ) != NULL ) {
      fputs( buff, stdout );
    }
    This will just dump the file to the screen.



    What you now do is build some logic into the while loop body to do more specialised work.

    If you want every other line, then do something like
    Code:
    if ( nlines % 2 ) == 0 ) fputs( buff, stdout );
    nlines++;
    If you want to print all lines beginning with 'a', then
    Code:
    if ( buff[0] == 'a' ) fputs( buff, stdout );
    If the logic is more complicated, then consider a FSM


    Perhaps paste an example of a .srt file, and perhaps use colours to highlight the bits of information you need to detect / extract.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #9
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by megareix View Post
    Thanks for the answers. Here is what I've got so far:

    Code:
    #include <stdio.h>
    
    main()
    {
       FILE *archivo;
       int linea = 1, i, num = 0;
       char ubicacion[60], linea2[40], *ptr, caracter;
    
       printf("ubication of the file: ");
       scanf("%s", ubicacion);
       if ((archivo = fopen(ubicacion, "r")) == NULL)
          printf("File could not be opened\n");
       else {
          while (1) {
             for (i = 1; i <= 4 && (fgetc(archivo) != EOF); i++) {
                if (i == 2) {
    		  caracter=fscanf(archivo,"%[^\n]\n",linea2); 
                      printf("%s\n", linea2);
                }
             }
          }
    
       }
    
       return 0;
    }
    But it doesn't work! As you can see, what it should do is print the second line, counting until the line 4, to start all over again and so forth. But it seems to print random line, not just the second line. I'm completely clueless about what's the problem. Oh, one more thing, I think I mentioned that I'm working with .srt files. I don't know if that affects the result so I think it's worth to mention.

    Thanks for all of your answers.

    I'm not sure what Salem is talking about regarding "Esbo's poison".
    I am not sure wha you want to do as you didn't specify it too clearly.
    Anyway this code below (untested) should print every second line.

    I'm not sure what the fgetc was doing, that reads a character and will skip over
    lines, printing a line ( or what remains of one) every four characters.
    I have never mixed getc and fscanf before, I would not advise it, either
    read a line at a time or a character as a time.
    Maybe you thought fgetc read a line? It's doesn't
    The fscanf as used, automatically puts you on the next line.


    Code:
    
    int linecounter=0;
    
    
    
        if ((archivo = fopen(ubicacion, "r")) == NULL)
          printf("File could not be opened\n");
       else {
          while (1) {
    		  caracter=fscanf(archivo,"%[^\n]\n",linea2); 
                      if (caracter==EOF) break;
    
                      linecounter++;
                      if (linecounter==2)  {
                           printf("%s\n", linea2);
                           linecounter=0;
                      }
                      
                }
             }

  10. #10
    In my head happyclown's Avatar
    Join Date
    Dec 2008
    Location
    In my head
    Posts
    391
    Quote Originally Posted by Salem View Post
    >
    Not entirely surprising given that you swallowed esbo's poison.
    Interesting choice of words.
    OS: Linux Mint 13(Maya) LTS 64 bit.

  11. #11
    Registered User
    Join Date
    Jan 2009
    Posts
    10
    Thanks for all of your answers. It still doesn't work, but I think I know why. I have been looking at the srt file, and it seems that it's not as straightforward as I thought. What I mean is not always the second line what I need to get. Here is an example of an .srt file:

    1
    00:00:58,475 --> 00:01:05,779
    bla bla bla bla bla bla bla bla

    2
    00:01:11,721 --> 00:01:15,157
    bla bla bla bla bla bla bla bla bla bla
    bla bla bla bla

    3
    00:01:15,291 --> 00:01:17,259
    bla bla bla
    bla bla bla bla bla bla bla.

    4
    00:01:21,197 --> 00:01:23,028
    bla bla bla bla.

    5
    00:01:23,166 --> 00:01:26,829
    bla bla bla bla bla

    6
    00:01:29,739 --> 00:01:32,173
    bla bla bla bla bla bla bla bla bla bla

    7
    00:01:42,352 --> 00:01:43,842
    bla

    8
    00:01:47,090 --> 00:01:49,251
    bla bla bla bla bla
    bla bla bla bla bla bla bla bla.
    The "bla bla bla" is supposed to be a random text, and it's not limited to just one line.
    An what I need to get is the line that looks like this: "00:00:58,475 --> 00:01:05,779".
    So the problem was kinda silly. But right now I don't know what approach to use.

  12. #12
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    So the whole point of the formatted input things is that they read formatted input.

    Code:
    while ( fgets( buff, sizeof buff, archivo ) != NULL ) {
      int success = sscanf(buff, "%d:%d:%d,%d --> %d:%d:%d,%d", &all, &your, &variables, &here);
      if (success==8) {
         //We read eight things so this is our line
      }
      //do it again!
    }

  13. #13
    Registered User
    Join Date
    Jan 2009
    Posts
    10
    Thank you for the answer tabstop. Here is the code using your suggestion:

    Code:
    #include <stdio.h>
    
    main()
    {
       FILE *archivo;
       int one, two, three, four, five, six, seven, eight, success;
       char ubicacion[60], buff[30];
    
       printf("ubicacion del archivo: ");
       scanf("%s", ubicacion);
       if ((archivo = fopen(ubicacion, "r")) == NULL)
          printf("File could not be opened\n");
       else {
            while ( fgets( buff, sizeof buff, archivo ) != NULL ) {
                 success = sscanf(buff, "%d:%d:%d,%d --> %d:%d:%d,%d", &one, &two, &three, &four, &five, &six, &seven, &eight);
                 if (success==8) {
                      printf("%d:%d:%d,%d --> %d:%d:%d,%d\n", &one, &two, &three, &four, &five, &six, &seven, &eight);
                 }
            }
       }
    
       return 0;
    }
    But it still doesn't work. What I get is this:

    -1073992452:-1073992456:-1073992460,-1073992464 --> -1073992468:-1073992472:-1073992476,-1073992480
    I get that over and over again. I don't know if I implemented your code in a wrong way or what. Hope someone can help me.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    This part is wrong and should have resulted in warnings:
    Code:
    printf("%d:%d:%d,%d --> %d:%d:%d,%d\n", &one, &two, &three, &four, &five, &six, &seven, &eight);
    You want to print the integers, not their addresses:
    Code:
    printf("%d:%d:%d,%d --> %d:%d:%d,%d\n", one, two, three, four, five, six, seven, eight);
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help is needed to read text from a file
    By yuzhangoscar in forum C Programming
    Replies: 12
    Last Post: 09-12-2008, 12:10 AM
  2. A bunch of Linker Errors...
    By Junior89 in forum Windows Programming
    Replies: 4
    Last Post: 01-06-2006, 02:59 PM
  3. reading a text file printing line number
    By bazzano in forum C Programming
    Replies: 4
    Last Post: 09-16-2005, 10:31 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM