C语言字符/字符串处理常用函数

fgetc() and fputc() in C

fgetc()

fgetc() is used to obtain input from a file single character at a time. This function returns the number of characters read by the function. It returns the character present at position indicated by file pointer. After reading the character, the file pointer is advanced to next character. If pointer is at end of file or if an error occurs EOF file is returned by this function.

int fgetc(FILE *pointer)
pointer: pointer to a FILE object that identifies 
the stream on which the operation is to be performed.
// C program to illustate fgetc() function 
#include <stdio.h> 

int main () 
{ 
	// open the file 
	FILE *fp = fopen("test.txt","r"); 

	// Return if could not open file 
	if (fp == NULL) 
	return 0; 

	do
	{ 
		// Taking input single character at a time 
		char c = fgetc(fp); 

		// Checking for end of file 
		if (feof(fp)) 
			break ; 

		printf("%c", c); 
	} while(1); 

	fclose(fp); 
	return(0); 
} 

  

Using fputc()

fputc() is used to write a single character at a time to a given file. It writes the given character at the position denoted by the file pointer and then advances the file pointer.
This function returns the character that is written in case of successful write operation else in case of error EOF is returned.

int fputc(int char, FILE *pointer)
char:  character to be written. 
This is passed as its int promotion.
pointer: pointer to a FILE object that identifies the 
stream where the character is to be written.
// C program to illustate fputc() function 
#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 bye", 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,20,fp); 

	printf("%s", received_string); 

	fclose(fp); 
	return 0; 
} 

  puts可以自动换行,printf不行;puts可以直接输出%s,printf不行

Problem with scanf() when there is fgets()/gets()/scanf() after it

Consider below simple program in C. The program reads an integer using scanf(), then reads a string using fgets().

// C program to demonstrate the problem when 
// fgets()/gets() is used after scanf() 
#include<stdio.h> 

int main() 
{ 
  int x; 
  char str[100]; 
  scanf("%d", &x); 
  fgets(str, 100, stdin); 
  printf("x = %d, str = %s", x, str); 
  return 0; 
} 

  

The problem with above code is scanf() reads an integer and leaves a newline character in buffer. So fgets() only reads newline and the string “test” is ignored by the program.

The similar problem occurs when scanf() is used in a loop.

// C program to demonstrate the problem when 
// scanf() is used in a loop 
#include<stdio.h> 

int main() 
{ 
	char c; 
	printf("......Enter q to quit......\n"); 
	do
	{ 
		printf("Enter a character\n"); 
		scanf("%c", &c); 
		printf("%c\n", c); 
	} 
	while (c != 'q'); 
	return 0; 
} 

  

We can notice that above program prints an extra “Enter a character” followed by an extra new line. This happens because every scanf() leaves a newline character in buffer that is read by next scanf.

How to solve above problem?

  1. We can make scanf() to read a new line by using an extra “\n”, i.e., scanf(“%d\n”, &x) . In fact scanf(“%d “, &x) also works (Note extra space).
  2. We can add a getchar() after scanf() to read an extra newline.

fgets() and gets() in C language

For reading a string value with spaces, we can use either gets() or fgets() in C programming language. Here, we will see what is the difference between gets() and fgets().

fgets()

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 :

char *fgets(char *str, int n, FILE *stream)
str : Pointer to an array of chars where the string read is copied.
n : Maximum number of characters to be copied into str 
(including the terminating null-character).
*stream : Pointer to a FILE object that identifies an input stream.
stdin can be used as argument to read from the standard input.

returns : the function returns str
  • It follow some parameter such as Maximum length, buffer, input device reference.
  • It is safe to use because it checks the array bound.
  • It keep on reading until new line character encountered or maximum limit of character array.

Example : Let’s say the maximum number of characters are 15 and input length is greater than 15 but still fgets() will read only 15 character and print it.

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

	return 0; 
} 

Since fgets() reads input from user, we need to provide input during runtime.

Input:
Hello and welcome to GeeksforGeeks

Output:
Hello and welc

gets()

Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached.
Syntax:

char * gets ( char * str );
str :Pointer to a block of memory (array of char) 
where the string read is copied as a C string.
returns : the function returns str
 
  • It is not safe to use because it does not check the array bound.
  • It is used to read string from user until newline character not encountered.

Example : Suppose we have a character array of 15 characters and input is greater than 15 characters, gets() will read all these characters and store them into variable.Since, gets() do not check the maximum limit of input characters, so at any time compiler may return buffer overflow error.

// C program to illustrate 
// gets() 
#include <stdio.h> 
#define MAX 15 

int main() 
{ 
	char buf[MAX]; 

	printf("Enter a string: "); 
	gets(buf); 
	printf("string is: %s\n", buf); 

	return 0; 
} 

  

Since gets() reads input from user, we need to provide input during runtime.

Input:
Hello and welcome to GeeksforGeeks

Output:
Hello and welcome to GeeksforGeeks

  

posted on 2019-05-10 20:39  EMH1899  阅读(227)  评论(0编辑  收藏  举报

导航