Does fgets auto null terminate?

This is a discussion on Does fgets auto null terminate? within the C Programming forums, part of the General Programming Boards category; Below is a bit of code which produces the following text: TestHello. Here Testis some text Testwhich is on the ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,344
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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, 10:27 AM
  4. linked list problem
    By kzar in forum C Programming
    Replies: 8
    Last Post: 02-05-2005, 03:16 PM
  5. opengl program as win API menu item
    By SAMSAM in forum Game Programming
    Replies: 1
    Last Post: 03-03-2003, 06:48 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21