Fputs and Fgets read and write files by line

Source: Internet
Author: User

1) Use of fputs

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
void Main ()
{
	int i = 0;
	FILE *FP = NULL;
	Char a[100] = "NBBBBCEJFMFMLMNKDFVN";
	Char *fname = "C:/1.txt";
	fp = fopen (fname, "r+");//r+ Read and write
	if (NULL = = fp)
	{
		printf ("Func fopen () err:%s\n", fname);
		return;
	}
        Fputs (A,FP);
	if (fp! = NULL)
	{
		fclose (FP);
	}
	System ("pause");	
}
2) Use of fgets

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
void Main ()
{
	int i = 0;
	FILE *FP = NULL;
	Char buf[100];
	char *p = NULL;
	Char *fname = "C:/1.txt";
	fp = fopen (fname, "R");
	if (NULL = = fp)
	{
		printf ("Func fopen () err:\n");
	}
	while (!feof (FP))
	{
		p = fgets (BUF,100,FP);//returns BUF's first address
		printf ("%s\n", p);
	}
	if (fp! = NULL)
	{
		fclose (FP);
	}
	System ("pause");	
}
Compared to the function name can be easily found differences, (FPUTC and Fgetc) VS (fputs and Fgets), C for Char, character, and S is the string, strings, so, fgets and fputs two functions for " Reads a C-style string from the input file into the character array and writes a C-style string to the output file.
The prototypes for the two functions are:
char * fgets (char * str, int n, FILE * fpin);
int fputs (const char * str, FILE *fpout);
Similarly, Fpin must be a file pointer opened in either read or read-only mode, and Fpout must be a file pointer opened in write, read-write, or append mode.
For the fgets function, n must be a positive integer, indicating that the number of characters read from the file is not more than n-1, stored in the character array str, and the end sign ' + ' at the end, in other words, n represents the length of the character array, or sizeof (str). If the read process encounters a newline character or a file end flag, the read operation ends. If read normally, returns a pointer to str that represents a string, otherwise returns null (NULL pointer).


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.