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

Threaded View

Previous Post Previous Post   Next Post Next Post
  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.

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