Programming with C

⌘K
  1. Home
  2. Docs
  3. Programming with C
  4. File Processing
  5. File Processing Operation...
  6. Get string from a file

Get string from a file

  • For reading a string value with spaces, we can use either gets() or fgets() in C programming language.
  • It reads a line from the specified stream and stores it into the string pointed to by str.
  • It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

Syntax

fgets
char *fgets(char *str, int n, FILE *stream)

Parameters

str âˆ’ This is the pointer to an array of chars where the string read is stored.

n âˆ’ This is the maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used.

stream − This is the pointer to a FILE object that identifies the stream where characters are read from.

Return value

  • On success, the function returns the same str parameter.
  • If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned.
  • If an error occurs, a null pointer is returned.

Program: Getting Input from Keyboard using fgets

#include <stdio.h>
#define MAX 15
int main()
{
    char buf[MAX];
    fgets(buf, MAX, stdin);
    printf("string is: %s\n", buf);
    return 0;
}

Output

Program: reading data from file using fgets

#include<stdio.h>
int main()
{
    int i = 0;
    FILE *fp = fopen("output.txt","w");
     // Return if could not open file
    if (fp == NULL)
      return 0;
     char string[] = "good work", received_string[20];
     for (i = 0; string[i]!='\0'; i++)
     {
        // Input string into the file
        // single character at a time
        fputc(string[i], fp);
      }
    fclose(fp);
    fp = fopen("output.txt","r");
     // Reading the string from file
    fgets(received_string,2,fp);
 
    printf("%s", received_string);
     fclose(fp);
    return 0;
}

Output

Program: reading data from file using fgets and print in stdout

#include<stdio.h>  
int main()
{  
	FILE *fp;  
	char text[300];  
	fp=fopen("output.txt","r");  
	printf("%s",fgets(text,200,fp));  
    fclose(fp);  
	return 0;  
}

Input

Output

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments