C – Reading String from File

Reading String from the file:

fgets() is used to read specified number of characters(String) at a time.

char*   fgets(char* str, int size, FILE* stream);

  • It reads “size” bytes from specified “stream” and stores into “str”.
  • On Success, it returns the pointer to string that has read.
  • On failure, it returns NULL pointer.
  • It reads only size-1 characters into String every time. Last character of every string is null(\0) by default.
#include<stdio.h>
int main()
{
            FILE* p;
            char str[10];
            p = fopen(“code.c”, “r”);
            if(p==NULL)
            {
                        printf(“No such file to open \n”);
            }
            else
            {
                        fgets(str, 10, p);
                        printf(“The string is : %s \n”, str);        
                        fclose(p);
            }
            return 0;
}

Reading the complete file using fgets():

#include<stdio.h>
int main()
{
            FILE* p;
            char str[10];
            p = fopen(“code.c”, “r”);
            if(p==NULL)
            {
                        printf(“No such file to open \n”);
            }
            else
            {
                        while(fgets(str, 10, p))
                        {
                                    printf(“%s \t”, str);
                        }          
                        fclose(p);
            }
            return 0;
}
Scroll to Top