Thread: Does fgets auto null terminate?

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    43

    Does fgets auto null terminate?

    Below is a bit of code which produces the following text:

    TestHello. Here
    Testis some text
    Testwhich is on the screen.

    What I would like to know is how the fgets function ends the string. Does it just stop, or is it automatically null terminated? i.e. for the first line of my output would s[13] = 0?

    Code:
    #include <stdio.h>
    
    int main()
    {
        FILE *f;
        char s[1000];
    
        f=fopen("file.txt","r");
        if (!f)
            return 1;
        while (fgets(s,1000,f)!=NULL)
     	{
    	printf("Test");       
    	printf("%s",s);
    }
        fclose(f);
        return 0;
    }

  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
    Yes, you always get a \0 in the result.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. addrinfo Structure Not Working
    By pobri19 in forum Networking/Device Communication
    Replies: 9
    Last Post: 10-22-2008, 10:07 AM
  2. Syntax Error??
    By Kennedy in forum C Programming
    Replies: 8
    Last Post: 09-06-2006, 11:04 AM
  3. Invalid conversion from 'void*' to 'BYTE' help
    By bikr692002 in forum C++ Programming
    Replies: 9
    Last Post: 02-22-2006, 11:27 AM
  4. linked list problem
    By kzar in forum C Programming
    Replies: 8
    Last Post: 02-05-2005, 04:16 PM
  5. opengl program as win API menu item
    By SAMSAM in forum Game Programming
    Replies: 1
    Last Post: 03-03-2003, 07:48 PM