Thread: fgets

  1. #1
    Registered User stautze's Avatar
    Join Date
    Apr 2002
    Posts
    195

    fgets

    I am using fgets like this:
    Code:
      fp=fopen("test.txt","r"); //open file
    
      while(fgets(string,'\n',fp) != NULL){
    
        count++;
    
        if(strcmp(string, start) == 0){
          printf("%s found at line %d\n", string, count );
      }
        }
    the problem is that I get the newline character too when I read each line of the file. I can't think of a good way to fix this.

    Thanks in advance for any ideas.
    'During my service in the United States Congress, I took the initiative in creating the Internet.' - Al Gore, March 9, 1999: On CNN's Late Edition

  2. #2
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    char *fgets(char *s, size_t n, FILE *stream);
    Ok, now the you have the prototype of the function, look at the second parameter, you should pass the size of the buffer, and not a char or everything else.

    Also, when you open a file, check if you really opened it, if you haven't any error
    Code:
    if ((fp = fopen("file.txt","r")) == NULL) {
        perror("Fopen: ");
        return EXIT_FAILURE;
    }
    
    else {
        //you can use the file
    }

  3. #3
    Registered User stautze's Avatar
    Join Date
    Apr 2002
    Posts
    195
    my mistake, I just typed that out as an example of what I was doing, and I haven't coded in a while.... but I am using the correct parameters when I call fgets, I just wanted to know who you can get rid of the "\n".
    'During my service in the United States Congress, I took the initiative in creating the Internet.' - Al Gore, March 9, 1999: On CNN's Late Edition

  4. #4
    .........
    Join Date
    Nov 2002
    Posts
    303
    Here is an example of how to eliminate a newline from an array.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int
    main(void)
    {
    	
    	char array[20];
    
    	fgets(array, sizeof(array), stdin);
    	
    	/* If there is a '\n' we remove it */
    	if (array[strlen(array)-1] == '\n') {
    		array[strlen(array)-1] = '\0';
    	}
    	else { /* If there isn't one, we know there is garbage */
    		while(getchar() != '\n'); 
    	}
    
    
    	return (0);
    }
    You could work with some variant of that, there are many more ways to remove newlines, many many more. For reading a file you could also read the file 1 character a time. Here is an example that removes every newline and stops reading at EOF, use Vbers example for checking if the file opened.
    Code:
    #include <stdio.h>
    
    int
    main(void)
    {
    	
    	FILE *input;
    	char data_line[BUFSIZ];
    	int subscript;
    
    	/* Open the file here and check for error like Vber showed */
    
    
    	for (subscript = 0;(data_line[subscript] = fgetc(input)) != EOF; subscript++){
    		if (data_line[subscript] == '\n') {
    		    data_line[subscript] = '\0';
    		}
    	}
    	return (0);
    }

  5. #5
    Registered User stautze's Avatar
    Join Date
    Apr 2002
    Posts
    195
    mahalo
    'During my service in the United States Congress, I took the initiative in creating the Internet.' - Al Gore, March 9, 1999: On CNN's Late Edition

  6. #6
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    actually fgets() leave an \n at the end of the buffer you're getting, always. You can use this code to remove the \n.

    Code:
    char *p;
    p = strchr(buf,'\n');
    if(p) *p = '\0';
    Once there was a nice thread talking about removing the \n from fgets.

    SourceCode wrote here some ways to do what you want

  7. #7
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    >actually fgets() leave an \n at the end of the buffer you're getting, always.

    No, not always.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char buffer[10];
        fputs("Prompt: ", stdout);
        fflush(stdout);
        if(fgets(buffer, sizeof(buffer), stdin) != NULL)
        {
            char *newline = strchr(buffer, '\n');
            if(newline != NULL)
            {
                puts("Found '\\n'. Replacing with '\\0'.");
                *newline = '\0';
            }
            else
            {
                int ch;
                puts("No '\\n' found. Eating excess characters:");
                do
                {
                    ch = getchar();
                    putchar(ch);
                } while(ch != '\n');
            }
            printf("buffer = \"%s\"\n", buffer);
        }
        return 0;
    }
    
    /* sample input/output
    Prompt: text
    Found '\n'. Replacing with '\0'.
    buffer = "text"
    
    Prompt: longer text
    No '\n' found. Eating excess characters:
    xt
    buffer = "longer te"
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  8. #8
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    You're trying to show what? that you put a buffer of 10 and enter a long string, you expect the function to work well? what should I tell? Nice for you? always when fgets() buffer can take succefully the string, he will add \n, change the size of your buffer to 100 and check.

    You're making something bad and expecting the function to works right, sorry, but this is kind stupid thing to do, use it with a proper buffer and he will add \n thats it.

    Well, It's really clear to understand that if he haven't size to add \n he won't add... that's obvious, but one thing I don't understand, \0 he add always am I right?
    Last edited by Vber; 03-17-2003 at 10:22 AM.

  9. #9
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    actually fgets() leave an \n at the end of the buffer you're getting, always.
    It's really clear to understand that if he haven't size to add \n he won't add... that's obvious.
    Your 2 sentences conflict each other, Dave was just pointing this out. And it's only obvious if you know the answer

    Put simply, you cannot guarantee that a \n will be in the buffer, so blindly placing \0 over the last byte of the string is a bad thing to do. But you know this already, so why are we having this conversation..?

    [edit]
    >>\0 he add always am I right?
    Yes, correct. \0 will always be present.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  10. #10
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    so blindly placing \0 over the last byte of the string is a bad thing to do
    Code:
    char *p;
    p = strchr(buf,'\n');
    if(p) *p = '\0';
    This is not blindly, and this is from the thread you showed me once, about removing \n of fgets(), remember?

    well, it's not needed to argue about this really
    Thanks dave for showing this, I really didn't express myself correctly.
    Last edited by Vber; 03-17-2003 at 10:29 AM.

  11. #11
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >what should I tell? Nice for you?
    No, you should thank him for informing you of your error. You should also not try to defend a mistake, if you do then you're the only one being fooled.

    [edit]
    >Thanks dave for showing this, I really didn't express myself correctly.
    nevermind
    [/edit]

    >always when fgets() buffer can take succefully the string, he will add \n
    Yes, but you didn't specify success previously, you said:
    actually fgets() leave an \n at the end of the buffer you're getting, always.
    Dave corrected you and showed you that your statement was not always true.

    >You're making something bad and expecting the function to works right, sorry, but this is kind stupid thing to do
    I disagree, you should attempt to break your code on purpose to make sure that it recovers or at least dies gracefully.

    >use it with a proper buffer and he will add \n thats it.
    A proper buffer being? char buffer[BUFSIZ]? I'm sorry, but no matter what size your buffer is, the chance is there that it will attempt to read a line that is too long.

    -Prelude
    My best code is written with the delete key.

  12. #12
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    No, you should thank him for informing you of your error. You should also not try to defend a mistake, if you do then you're the only one being fooled.
    [edit]saw your post [/edit]
    Yes, but you didn't specify success previously, you said:
    I really didn't express myself correctly.
    Dave corrected you and showed you that your statement was not always true.
    And what I told him?
    And what another thing I told here in the thread?
    well, it's not needed to argue about this really
    Well

  13. #13
    Registered User
    Join Date
    Feb 2003
    Posts
    8

    strtok()

    /* Create a "proper" buffer */
    char string[640K_OUGHT_TO_BE_ENOUGH_FOR_ANYBODY];
    fgets(string,sizeof(string),stdin);
    strtok(string,"\n"); /* Will replace the first newline in string with a NULL */
    Last edited by Heraclitus; 03-17-2003 at 01:03 PM.

  14. #14
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    One of the things I was trying to point out, and which was included in the code posted by SourceCode, was the handling of the case in which the input exceeds the buffer size. Text remains in stdin. Not handling it may be a bug, much like the issue with '\n' and scanf.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    char *foo(char *buffer, size_t size, const char *prompt)
    {
        if ( buffer != NULL )
        {
            if ( prompt != NULL )
            {
                fputs(prompt, stdout);
                fflush(stdout);
            }
            if ( fgets(buffer, size, stdin) != NULL )
            {
                char *newline = strchr(buffer, '\n');
                if ( newline != NULL )
                {
                    *newline = '\0';
                }
    #if 0
                else
                {
                    while ( getchar() != '\n' ) { /* consume leftovers */ }
                }
    #endif
            }
        }
        return buffer;
    }
    
    int main(void)
    {
        char buffer[10] = "";
        while ( *buffer != '0' )
        {
            printf("buffer = \"%s\"\n", foo(buffer, sizeof(buffer), "prompt: "));
        }
        return 0;
    }
    
    /* sample input/output #if 0
    prompt: This text is really, really, really long. Bigger than the buffer size.
    buffer = "This text"
    prompt: buffer = " is reall"
    prompt: buffer = "y, really"
    prompt: buffer = ", really "
    prompt: buffer = "long. Big"
    prompt: buffer = "ger than "
    prompt: buffer = "the buffe"
    prompt: buffer = "r size."
    prompt: 0
    buffer = "0"
    */
    
    /* sample input/output #if 1
    prompt: This text is really, really, really long. Bigger than the buffer size.
    buffer = "This text"
    prompt: 0
    buffer = "0"
    */
    Several searches show that I've left this out a number of times, so I thought it was worth menthioning.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  15. #15
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    /* Create a "proper" buffer */
    char string[640K_OUGHT_TO_BE_ENOUGH_FOR_ANYBODY];
    Ooh, good one. Would be better if identifiers could begin with a digit.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets not working after fgetc
    By 1978Corvette in forum C Programming
    Replies: 3
    Last Post: 01-22-2006, 06:33 PM
  2. problem with fgets
    By learninC in forum C Programming
    Replies: 3
    Last Post: 05-19-2005, 08:10 AM
  3. problem with fgets
    By Smoot in forum C Programming
    Replies: 4
    Last Post: 12-07-2003, 03:35 AM
  4. fgets crashing my program
    By EvBladeRunnervE in forum C++ Programming
    Replies: 7
    Last Post: 08-11-2003, 12:08 PM
  5. help with fgets
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 10-17-2001, 08:18 PM