Thread: C program to find a line in a file and print it

  1. #1
    Registered User
    Join Date
    Dec 2016
    Posts
    96

    C program to find a line in a file and print it

    Hi!

    I can write a program to find a string in a file, write it to a different file, increment an int number in the file. But I can't find an example to find a line in a file which contains the string I need and then print the whole line.

    Example:
    search for String: 0x22 0x023 0x24
    if String is found on line 9
    print the whole line 9, or print until you find a custom terminating character like "0x9999 "

    result must be: print 0x22 0x23 0x24 0x25 0x26 0x27 0x28.


    Code:
    #include <stdio.h>
    
    int main(void)
    {
      FILE *ifp, *ofp;
      char *mode = "r";
      char outputFilename[] = "out.list";
      char username[9];  /* One extra for nul char. */
      int score;
    
      ifp = fopen("in.list", mode);
    
      if (ifp == NULL) {
        fprintf(stderr, "Can't open input file in.list!\n");
        exit(1);
      }
    
      ofp = fopen(outputFilename, "w");
    
      if (ofp == NULL) {
        fprintf(stderr, "Can't open output file %s!\n", outputFilename);
        exit(1);
      }
    
      while (fscanf(ifp, "%s %d", username, &score) == 2) {
        fprintf(ofp, "%s %d\n", username, score+10);
      }
    
      fclose(ifp);
      fclose(ofp);
    
      return 0;
    }
    EDIT:
    The simplest best I found is to find the string I am looking for(0x22 0x23 0x24 in this case) and print until the custom terminating character, but I don't how does the auto incrementation of fscanf will work in this case and I want to know the other case too.
    Last edited by ArakelTheDragon; 03-17-2020 at 03:25 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    strstr() finds one string inside another.
    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.

  3. #3
    Registered User
    Join Date
    Dec 2016
    Posts
    96

    Result

    I tried with strcmp () which should return the number of the same characters, but there is some logical mistake in my structure of the code I think:

    Main code:
    Code:
               case 4:
                    printf ("This program simulates finding a string in a file and printing the whole line.\n");
                    printf ("Please enter the request:\n");
                    scanf ("%s", cpTemporaryString_5);
                    FindStringInFile (cpTemporaryString_5);
    Function code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #include "Y:/Other/Library_OS/Functions.h"  // List of the functions.
    
    int FindStringInFile (char *Request)
    {
                                                                                // Local variables
      unsigned int i = 0;                                                        // Counter.
      unsigned int ByteSize = 0;                                                // Will store the byte size for the response and request.
      char c;
      FILE *ifp;                                                                // Define pointers which point to type FILE.
      char *mode = "r";                                                            // Open file for reading. Define pointer to char with value r.
      char Inputfilename[] = "Database.cfc";                                    // Define an array to the file name with value out.list.
      char *RequestResponse;
                                                                                // Open files and opening error block.
      ifp = fopen(Inputfilename, mode);
    
      if (ifp == NULL) {                                                        // If in.list can not be opened for reading.
        fprintf(stderr, "Can't open input file in.list!\n");                    // Print the file can not be opened.
        exit(1);                                                                // Exit with error code 1.
      }
                                                                                //Processing
        while ((c = fgetc (ifp)) != EOF){
            i = 0;
            while ((c = fgetc (ifp)) != '\n'){
                RequestResponse [i] = c;                                        // Arrays and pointers are interchangable.
                i++;
            }
            RequestResponse [i] = '\0';                                            // Arrays and pointers are interchangable.
            if (strcmp (Request, RequestResponse) > 16)                         // The first 17 characters must be the same.
                printf ("The result is: %s", RequestResponse);
        }
      fclose(ifp);
    
      return 0;
    }
    The result is:
    Code:
    Process returned -1073741819 (0xC0000005)   execution time : 6.915 s
    Press any key to continue.
    Last edited by ArakelTheDragon; 03-17-2020 at 07:37 AM. Reason: Post the result, remove the unnecessary parts and make the code more readable.

  4. #4
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    You're just inventing how strcmp works.
    Where did you read it returns a count of matching characters?
    It's return value is 0 if ALL characters match.
    It returns a negative (but otherwise meaningless) value if the lhs string is typographically less than the rhs string.
    It returns a positive (but otherwise meaningless) value if the lhs is greater than the rhs.

    Use the proper tools and your simple problem is, as it should be, simple.
    Code:
    void FindStringInFile (const char *filename, const char* request)
    {
        FILE *fin = fopen(filename, "r");
        if (!fin)
        {
            perror("FindStringInFile: cannot open file");
            exit(EXIT_FAILURE);
        }
        
        char line[1024];
        while (fgets(line, sizeof line, fin))
            if (strstr(line, request))
                printf("%s", line);
    
        fclose(fin);
    }
    Last edited by john.c; 03-17-2020 at 09:07 AM. Reason: added fclose(fin)
    A little inaccuracy saves tons of explanation. - H.H. Munro

  5. #5
    Registered User
    Join Date
    Dec 2016
    Posts
    96
    Believe me, its not that I don't want to, but I don't have the option to. And the second problem is that it does not work:

    Code:
    Process returned -1073741819 (0xC0000005)   execution time : 8.455 s
    Press any key to continue.

  6. #6
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    945
    Quote Originally Posted by ArakelTheDragon View Post
    Believe me, its not that I don't want to, but I don't have the option to.
    What don't you have the option to do and why don't you have the option? Help us help you by being clear on what problem(s) you're facing.

  7. #7
    Registered User
    Join Date
    Jun 2019
    Posts
    44
    Maybe this could help.

    john2.c

    Code:
    #include <stdio.h>
    #include <stdbool.h>
    #include <string.h>
    
    int main()
    {
    
    FILE *fptr,*fptw;
    
          fptr=fopen("src.txt","r");
          fptw=fopen("dest.txt","w");
     
        char line_b0[1000];
        bool printline_b0=false;
    
        while (fgets(line_b0, sizeof line_b0, fptr) != NULL) {
            if (printline_b0) {
                fputs(line_b0, fptw);
                printline_b0=false; }
           
            if (strstr(line_b0, "hello") != NULL) {            /** below */
                printline_b0=true;  }  }
        fclose(fptr);
        fclose(fptw);
    
        return 0;
    }
    src.txt
    hello
    0x22 0x23
    hello
    0x24
    hello where are the rest
    with me. 0x25 0x26 0x27 0x28.

    You can change it to find something above. First step now completed or fix it to do more again. From there you format it the way you like. I use john.c code all day long.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > Process returned -1073741819 (0xC0000005) execution time : 6.915 s
    Yes, your badly constructed double while loop failed to spot the end of file correctly, so it spent the next 5 to 10 seconds rapidly overwriting memory it doesn't own until the OS finally decided it had had enough of your code.

    Just use a while ( fgets ( construct to read whole lines for you.

    > // The first 17 characters must be the same.
    Then use strncmp, as in
    Code:
    if ( strncmp(a,b,17) == 0 ) {
      // 
    }
    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
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    Don't just say "and the second problem is that it does not work". Of course it "works". Post your broken code that you actually ran so we can show you your error.
    Last edited by john.c; 03-18-2020 at 09:56 AM.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  10. #10
    Registered User
    Join Date
    Dec 2016
    Posts
    96
    I did post it. Also it seams on Windows 10 the standard C libraries do not work well. strcpy (), strcmp (), itoa () and others lead to terminating the program. I will try to re-write the code and give some final version. I am beginning to think GCC is not good.

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ArakelTheDragon
    Also it seams on Windows 10 the standard C libraries do not work well. strcpy (), strcmp (), itoa () and others lead to terminating the program. I will try to re-write the code and give some final version. I am beginning to think GCC is not good.
    I hate to say this, but... while it has its fair share of bugs, GCC is probably fine. It is your code that is not good.

    For example, now that I can see that you updated post #3 with the code that you tried, it is painfully obvious that you dereferenced RequestResponse before setting it to point to something valid. You probably made similiar mistakes when using strcpy, strcmp, etc. These kinds of mistakes on your part (absolutely not the fault of the compiler) can "lead to terminating the program" prematurely.
    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

  12. #12
    Registered User
    Join Date
    Aug 2019
    Location
    inside a singularity
    Posts
    308
    That's false, wherever you heard it. As long as your code is correct, you won't face any problems. Either your code is badly written or your code is badly written. That's the only reason why your program crashes. Write "good" code and GCC will give you exactly what you need.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." - Rick Cook, The Wizardry Compiled

  13. #13
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    +1 for laserlight for spotting the pointer issue

    @ArakelTheDragon, compile with many warnings enabled and make sure you FIX all of them before running the code.
    Code:
    $ gcc -c -Wall -Wextra bar.c
    bar.c: In function ‘FindStringInFile’:
    bar.c:8:16: warning: unused variable ‘ByteSize’ [-Wunused-variable]
       unsigned int ByteSize = 0;                                                // Will store the byte size for the response and request.
                    ^
    bar.c:25:29: warning: ‘RequestResponse’ may be used uninitialized in this function [-Wmaybe-uninitialized]
                 RequestResponse [i] = c;                                        // Arrays and pointers are interchangable.
                                 ^
    > Arrays and pointers are interchangable.
    This piece of nonsense is where you're coming unstuck.
    Arrays and Pointers
    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.

  14. #14
    Registered User
    Join Date
    Dec 2016
    Posts
    96
    Ok, this is the simplest version. And still it does not work, it compiles with no errors, but by now I am so tired that I might be missing the obvious.

    Code:
                                                        // Built-in library includes //
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <stdbool.h>
                                                        // Custom includes //
    #include "Y:/Other/Library_OS/Functions.h"          // List of the functions.
    
    int main (void)
    {
                                                        // Local variables //
        FILE *fpFilePointer;                            // Declare a pointer to a type file.
    
        fpFilePointer=fopen("Database.cfc","r");        // Open the file for reading.
    
        char LineStorage[1024];                         // Store 1 line in the buffer.
    
        while (fgets(LineStorage, strlen (LineStorage), fpFilePointer) != NULL)
            if (strstr(LineStorage, "0x22") != NULL)
                puts ("LineStorage");
    
    
        fclose(fpFilePointer);                          // All files must be closed.
    
        return 0;
    }

  15. #15
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    945
    Quote Originally Posted by ArakelTheDragon View Post
    Code:
     
        char LineStorage[1024];                         // Store 1 line in the buffer.
    
        while (fgets(LineStorage, strlen (LineStorage), fpFilePointer) != NULL)
    LineStorage is uninitialized the first time fgets is called, so you can't use strlen on it. Besides, you don't want to know how long the string is; you want to pass the size of (hint) the LineStorage array to fgets.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 06-02-2017, 04:00 PM
  2. Reading from a file and print in a different line
    By Giwrgows x in forum C Programming
    Replies: 3
    Last Post: 12-25-2015, 08:03 AM
  3. trying to print a line from a text file
    By kryonik in forum C++ Programming
    Replies: 1
    Last Post: 06-06-2006, 09:14 PM
  4. print line by line from a file
    By SoFarAway in forum C Programming
    Replies: 3
    Last Post: 02-18-2005, 01:36 PM

Tags for this Thread