Thread: Problem with fgets and double printing

  1. #1
    Registered User
    Join Date
    Feb 2020
    Posts
    1

    Question about fgets/arrays

    Hello! I'm trying to read from a text file that's being redirected to my program.

    Code:
    ./program < test.txt
    The code looks like this:
    Code:
      // read redirection
      char buffer[50][200] = {0};
    
      int size = 0;
      while(fgets(buffer[size], 200, stdin) != NULL) {
        printf("%s", buffer[size]);
        size++;
      }
      
      printf("\nPrinting Array\n");
      for(int i=0; i < size; i++) {
        printf("%s", buffer[i]);
      }
    
    Is this the best way to do it? I feel like I have a lot of extra space/size because I'm not sure how long the commands or text file will be. Should I be reading the length of the text file somehow?

    Additionally, I thought of setting the last element to NULL, but apparently I can't do something along the lines of
    Code:
    buffer[size+1] = NULL;
    Why exactly does C stop me from doing this? And how would I mark the end of the buffer array?
    Last edited by verqe; 02-27-2020 at 01:32 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Double printing on the screen problem. Help needed.
    By Scantymix in forum C Programming
    Replies: 6
    Last Post: 04-15-2014, 05:20 AM
  2. Printing individual characters from fgets using an array
    By SneakySnake in forum C Programming
    Replies: 1
    Last Post: 12-07-2012, 12:07 AM
  3. Problem with printing double numbers
    By stdq in forum C Programming
    Replies: 7
    Last Post: 01-28-2012, 03:08 AM
  4. Printing Double?
    By IKnew in forum C++ Programming
    Replies: 7
    Last Post: 09-28-2010, 03:41 PM
  5. Printing a double forwardslash...?
    By fraktal in forum C Programming
    Replies: 11
    Last Post: 01-18-2006, 04:10 PM

Tags for this Thread