C Language File Operation function Daquan (super verbose)

Source: Internet
Author: User
Tags define function fread rewind string format

C Language File Operation function Daquan (ultra-verbose) font: [Increase decrease] Type: Reproduced this article is the C language in the file operation function of a detailed summary analysis, the need for a friend reference

fopen (Open file)
Correlation function Open,fclose
Table header file #include <stdio.h>
Defines the function FILE * fopen (const char * path,const char * mode);
Function description The path string contains the file path and filename to open, and the parameter mode string represents the flow pattern.
Mode has the following pattern strings:
R to open a read-only file, the file must exist.
r+ open a writable file, the file must exist.
W Open Write-only file, if the file exists then the file length is clear to 0, that is, the contents of the file will disappear. If the file does not exist, the file is created.
w+ Open a read-write file, if the file exists then the file length is clear to zero, that is, the contents of the file will disappear. If the file does not exist, the file is created.
A write-only file opens in an additional way. If the file does not exist, the file will be created, and if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained.
A + opens readable and writable files in an additional way. If the file does not exist, the file will be created, and if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained.

Copy CodeThe code is as follows:
R Open text file for reading. The stream is positioned at the beginning of the file.
r+ Open for reading and writing. The stream is positioned at the beginning of the file.
W Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
w+ Open for reading and writing.  The file is created if it does isn't exist, otherwise it is truncated. The stream is posi‐
Tioned at the beginning of the file.
A Open for appending (writing at end of file).  The file is created if it does not exist. The stream is positioned at the
End of the file.
A + Open for reading and appending (writing at end of file).  The file is created if it does not exist. The initial file posi‐
tion for reading was at the beginning of the file, but output was always appended to the end of the file.


These morphological strings can be added with a B character, such as RB, w+b, or ab+ combinations, and a B character is used to tell the library that the file opened is a binary file, not a plain text file. However, in a POSIX system, including Linux ignores the character. A new file created by fopen () will have a s_irusr| s_iwusr| s_irgrp| s_iwgrp| s_iroth| S_iwoth (0666) permission, this file permission will also refer to the Umask value.
When the return value file is opened successfully, the file pointer to the stream is returned. If the file fails to open, it returns null and the error code exists in errno.
Additional instructions in general, after opening the file will make some file read or write action, if the file fails, the next read and write action can not be carried out smoothly, so after fopen () Please make error judgment and processing.
Example

Copy CodeThe code is as follows:
#include <stdio.h>
Main ()
{
FILE * FP;
Fp=fopen ("Noexist", "A +");
if (fp= =null) return;
Fclose (FP);
}


1. fprintf
Function: Transfer formatted output to a file
Table header files: #include <stdio.h>
function prototypes: int fprintf (FILE *stream, char *format[, argument,...]);
file* A pointer to a file type
char* format the input function, as in printf
Return value: Returns the number of bytes converted on success, and returns a negative when failed
fp = fopen ("/local/test.c", "A +");
fprintf (FP, "%s\n", str);

2. fscanf
Function: Performs a formatted input from a stream
Table header files: #include <stdio.h>
function prototypes: int fscanf (FILE *stream, char *format[,argument ...]);
file* A pointer to a file type
char* formatted output function, as in the scanf format
Return value: Returns the number of bytes converted on success, and returns a negative when failed
fp = fopen ("/local/test.c", "A +");
FSCANF (FP, "%s", str);

3. Clearerr (Error flag to clear file stream)
Correlation function feof
Table header file #include <stdio.h>
Defines the function void Clearerr (FILE * stream);
The function Description Clearerr () Clears the error flag used by the file stream specified by the parameter stream.
return value
 
4.fclose (Close file)
Correlation function Close,fflush,fopen,setbuf
Table header file #include <stdio.h>
Defines the function int fclose (FILE * stream);
The function Description fclose () is used to close the file opened by the previous fopen (). This action causes the data in the buffer to be written to the file and frees the file resources provided by the system.
The return value returns 0 if the close file action succeeds, and when an error occurs, it returns EOF and saves the error code to errno.
The error code EBADF indicates that the parameter stream is not an open file.
For example, refer to fopen ().
 
5.fdopen (convert file descriptor to file pointer)
Correlation function Fopen,open,fclose
Table header file #include <stdio.h>
Define the function FILE * fdopen (int fildes,const char * mode);
The function Description Fdopen () Converts the file descriptor of the parameter fildes to the corresponding file pointer and returns. The parameter mode string represents the flow pattern of the file pointer, which must be the same as the original file descriptor read-write mode. For the mode string format, refer to fopen ().
Returns a file pointer to the stream when the return value conversion succeeds. Failure returns NULL, and the error code is present in errno.
Example

Copy CodeThe code is as follows:
#include <stdio.h>
Main ()
{
FILE * FP =fdopen (0, "w+");
fprintf (FP, "%s/n", "hello!");
Fclose (FP);
}
Executive Hello!


6.feof (check that the file stream is read to the end of the file)
related functions fopen,fgetc,fgets, Fread
Header file #include <stdio.h>
defines the function int feof (file * stream);
The function Description feof () is used to detect if the end of the file is read, and the mantissa stream is the file pointer returned by fopen (). If a value other than 0 is returned to the end of the file, 0 is returned. The
return value returns a non-0 value that represents the end of the file reached.

7.fflush (update buffer)
related functions write,fopen,fclose,setbuf
header file #include <stdio.h>
defines the function int fflush (file* stream);
The function Description Fflush () forces the data in the buffer to be written back to the file specified in the parameter stream. If the parameter stream is Null,fflush (), all open file data is updated. The
return value successfully returns 0, the failure returns EOF, and the error code is stored in errno. The
error code EBADF parameter stream specifies that the file is not open, or that the open state is read-only. Other error codes refer to write ().

8.fgetc (a character read by a file)
related functions open,fread,fscanf, GETC
Header file Include<stdio.h>
defines the function NT fgetc (file * stream);
Function Description fgetc () reads a character from the file that the parameter stream refers to. If you read the end of the file and have no data, you return EOF. The
Return value GETC () returns the read character and, if it returns EOF, to the end of the file.
Example

Copy CodeThe code is as follows:
#include <stdio.h>
Main ()
{
FILE *FP;
int C;
Fp=fopen ("exist", "R");
while ((C=FGETC (FP))!=eof)
printf ("%c", c);
Fclose (FP);
}


9.fgets (reads a string from the file)
Correlation function Open,fread,fscanf,getc
Table header File include<stdio.h>
Define Function Har * fgets (char * s,int size,file * stream);
The function Description fgets () is used to read the characters from the file referred to in the parameter stream to the memory space referred to by the parameter S, until a newline character is present, the end of the file is read, or the size-1 character is read, and then NULL is terminated as a string.
return value gets () returns the S pointer if successful, and returns null to indicate an error occurred.
Example

Copy CodeThe code is as follows:
#include <stdio.h>
Main ()
{
Char s[80];
Fputs (Fgets (S,80,stdin), stdout);
}
Execute this is a test/* input */
This is a test/* output */


10.fileno (returns the file descriptor used by the file stream)
Correlation function Open,fopen
Table header file #include <stdio.h>
Defines the function int Fileno (FILE * stream);
The function Description Fileno () is used to obtain the file descriptor used by the stream specified by the parameter stream.
The return value returns the file description word.
Example

Copy CodeThe code is as follows:
#include <stdio.h>
Main ()
{
FILE * FP;
int FD;
Fp=fopen ("/etc/passwd", "R");
Fd=fileno (FP);
printf ("fd=%d/n", FD);
Fclose (FP);
}
Executive Fd=3


12.FPUTC (writes a specified character to the file stream)
Correlation function FOPEN,FWRITE,FSCANF,PUTC
Table header file #include <stdio.h>
Defines the function int FPUTC (int c,file * stream);
The function Description FPUTC will convert the parameter C to unsigned char after writing to the file specified in the parameter stream.
The return value FPUTC () returns the character that was successfully written, that is, parameter C. Returning EOF indicates a write failure.
Example

Copy CodeThe code is as follows:
#include <stdio.h>
Main ()
{
FILE * FP;
Char a[26]= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i;
fp= fopen ("Noexist", "w");
for (i=0;i<26;i++)
FPUTC (A,FP);
Fclose (FP);
}


13.fputs (writes a specified string to the file)
Correlation function FOPEN,FWRITE,FSCANF,FPUTC,PUTC
Table header file #include <stdio.h>
Defines the function int fputs (const char * s,file * stream);
The function Description fputs () is used to write the string that the parameter s refers to in the file referred to by the parameter stream.
The return value, if successful, returns the number of characters written out, and the return EOF indicates an error occurred.
For example, refer to Fgets ().
Fread (reading data from a file stream)
Correlation function fopen,fwrite,fseek,fscanf
Table header file #include <stdio.h>
Define function size_t fread (void * ptr,size_t size,size_t nmemb,file * stream);
The function Description Fread () is used to read data from the file stream. The parameter stream is an open file pointer, and the parameter PTR points to the data space to hold the read in, and the number of characters read is determined by the parameter size*nmemb. Fread () returns the number of Nmemb actually read, and if this value is smaller than the parameter nmemb, the representative may have read the end of the file or an error occurred, and must use feof () or ferror () to determine what happened.
The return value returns the number of Nmemb actually read.
Additional Instructions
Example

Copy CodeThe code is as follows:
#include <stdio.h>
#define NMEMB 3
struct test
{
Char name[20];
int size;
}S[NMEMB];
int main () {
FILE * stream;
int i;
stream = fopen ("/tmp/fwrite", "R");
Fread (s,sizeof (struct test), nmemb,stream);
Fclose (stream);
for (i=0;i<nmemb;i++)
printf ("name[%d]=%-20s:size[%d]=%d/n", i,s.name,i,s.size);
}
Perform
name[0]=linux! Size[0]=6
name[1]=freebsd! Size[1]=8
name[2]=windows2000 size[2]=11


14.freopen (Open file)
Correlation function Fopen,fclose
Table header file #include <stdio.h>
Defines the function FILE * freopen (const char * path,const char * mode,file * stream);
Function description parameter The path string contains the file paths and filenames to open, and the parameter mode please refer to the fopen () description. The parameter stream is an open file pointer. Freopen () closes the file stream opened by the original stream, and then opens the file for the parameter path.
When the return value file is opened successfully, the file pointer to the stream is returned. Returns null if the file fails to open, and the error code exists in errno.
Example

Copy CodeThe code is as follows:
#include <stdio.h>
Main ()
{
FILE * FP;
Fp=fopen ("/etc/passwd", "R");
Fp=freopen ("/etc/group", "R", FP);
Fclose (FP);
}


15.fseek (move the Read and write location of the file stream)
Correlation function Rewind,ftell,fgetpos,fsetpos,lseek
Table header file #include <stdio.h>
Defines the function int fseek (FILE * stream,long offset,int whence);
The function Description fseek () is used to move the read and write location of the file stream. The parameter stream is an open file pointer, and the parameter offset is the number of displacements that move the read-write position according to the parameter whence.
The parameter whence is one of the following:
Seek_set the offset offset from the beginning of the file to the new read-write location. The seek_cur increases the offset displacement by the current read and write position.
Seek_end points the read and write position to the end of the file and then increments the offset displacement.
When the whence value is Seek_cur or seek_end, the parameter offset allows negative values to appear.
The following are the more specific ways to use:
1) to move the read-write location to the beginning of the file: fseek (file *stream,0,seek_set);
2) to move the read-write location to the end of the file: fseek (file *stream,0,0seek_end);
Returns 0 when the worth call succeeds, and returns -1,errno if there is an error code.
Additional Instructions fseek () do not return to read-write locations like Lseek (), so you must use Ftell () to get the current read and write locations.
Example

Copy CodeThe code is as follows:
#include <stdio.h>
Main ()
{
FILE * stream;
Long offset;
fpos_t POS;
Stream=fopen ("/etc/passwd", "R");
Fseek (Stream,5,seek_set);
printf ("offset=%d/n", Ftell (stream));
Rewind (stream);
Fgetpos (Stream,&pos);
printf ("offset=%d/n", POS);
pos=10;
Fsetpos (Stream,&pos);
printf ("offset =%d/n", Ftell (stream));
Fclose (stream);
}
Perform offset = 5
Offset =0
offset=10


16.ftell (Gets the read location of the file stream)
Correlation function Fseek,rewind,fgetpos,fsetpos
Table header file #include <stdio.h>
Defines the function long Ftell (FILE * stream);
The function Description Ftell () is used to obtain the current read and write location of the file stream. The parameter stream is an open file pointer.
Returns the current read-write location when the worth call succeeds, and returns -1,errno if there is an error code.
Error code EBADF the stream of invalid or movable read and write locations for the parameter stream.
Example reference fseek ().
 
17.fwrite (writes data to a file stream)
Correlation function fopen,fread,fseek,fscanf
Table header file #include <stdio.h>
Defines the function size_t fwrite (const void * ptr,size_t size,size_t nmemb,file * stream);
The function Description fwrite () is used to write data to the file stream. The parameter stream is an open file pointer, and the parameter PTR points to the data address to be written, and the number of characters written in total is determined by the parameter size*nmemb. Fwrite () returns the number of Nmemb actually written.
The return value returns the number of Nmemb actually written.
Example

Copy CodeThe code is as follows:
#include <stdio.h>
#define SET_S (x, y) {Strcoy (s[x].name,y); S[x].size=strlen (y);}
#define NMEMB 3
struct test
{
Char name[20];
int size;
}S[NMEMB];
Main ()
{
FILE * stream;
set_s (0, "linux!");
set_s (1, "freebsd!");
set_s (2, "Windows2000.");
Stream=fopen ("/tmp/fwrite", "w");
Fwrite (s,sizeof (struct test), nmemb,stream);
Fclose (stream);
}
perform reference fread ().


18.GETC (read one character from the file)
Correlation function Read,fopen,fread,fgetc
Table header file #include <stdio.h>
Defines the function int getc (FILE * stream);
The function Description getc () is used to read a character from the file referred to in the parameter stream. If you read the end of the file and have no data, you return EOF. Although Getc () works the same as fgetc (), getc () is defined as a macro and is not a real function call.
The return value GETC () returns the read character and, if it returns EOF, to the end of the file.
Example reference fgetc ().
 
19.getchar (one character read in the standard input device)
Correlation function Fopen,fread,fscanf,getc
Table header file #include <stdio.h>
Defines the function int getchar (void);
The function Description GetChar () is used to read a character from a standard input device. The character is then returned from unsigned char to int.
The return value GetChar () returns the read character and, if EOF is returned, indicates an error occurred.
Additional Description GetChar () is not a real function, but a getc (STDIN) macro definition.
Example

Copy CodeThe code is as follows:
#include <stdio.h>
Main ()
{
FILE * FP;
int c,i;
for (i=0li<5;i++)
{
C=getchar ();
Putchar (c);
}
}
Execute 1234/* input */
1234/* Output */


20.gets (read in a string from the standard input device)
Correlation function Fopen,fread,fscanf,fgets
Table header file #include <stdio.h>
define function char * gets (char *s);
The function description gets () is used to read the characters from the standard device to the memory space referred to by the parameter S, until a newline character is present, or until the end of the file is read, and the end is followed by NULL as the string.
return value gets () returns the S pointer if successful, and returns null to indicate an error occurred.
Additional note because the get () cannot know the size of the string s, you must encounter a newline character or end of the file to terminate the input, so it is easy to create a buffer overflow security issue. It is recommended to use Fgets () instead.
Example Reference fgets ()
 
21.mktemp (generates a unique temporary file name)
Correlation function Tmpfile
Table header file #include <stdlib.h>
define function char * mktemp (char * template);
The function Description Mktemp () is used to produce a unique temporary file name. The last six characters in the file name string that the parameter template refers to must be xxxxxx. The resulting file name is returned by a string pointer.
When the return value file is opened successfully, the file pointer to the stream is returned. Returns null if the file fails to open, and the error code exists in errno.
additional Description parameter template The file name string that is referred to must be declared as an array, such as:
Char template[]= "template-xxxxxx";
Do not use char * template= "template-xxxxxx";
Example

Copy CodeThe code is as follows:
#include <stdlib.h>
Main ()
{
Char template[]= "template-xxxxxx";
Mktemp (template);
printf ("template=%s/n", template);
}


22.PUTC (writes a specified character to the file)
Correlation function FOPEN,FWRITE,FSCANF,FPUTC
Table header file #include <stdio.h>
Defines the function int putc (int c,file * stream);
The function Description PUTC () converts the parameter C to unsigned char and writes the parameter to the file specified by the stream. Although PUTC () works the same as FPUTC (), PUTC () is defined as a macro and is not a real function call.
The return value PUTC () returns the character that was successfully written, that is, parameter C. Returning EOF indicates a write failure.
Example Reference FPUTC ().
 
23.putchar (writes the specified characters to the standard output device)
Correlation function FOPEN,FWRITE,FSCANF,FPUTC
Table header file #include <stdio.h>
Defines the function int putchar (int c);
The function Description Putchar () is used to write the parameter C character to the standard output device.
The return value Putchar () returns the output success character, which is parameter C. Returning EOF indicates that the output failed.
Additional Description Putchar () is not a real function, but a PUTC (C,STDOUT) macro definition.
Example Reference GetChar ().
 
24.rewind (resets the read and write location of the file stream to the beginning of the file)
Correlation function Fseek,ftell,fgetpos,fsetpos
Table header file #include <stdio.h>
Defines the function void rewind (FILE * stream);
The function Description Rewind () is used to move the read and write location of the file stream to the beginning of the file. The parameter stream is an open file pointer. This function is equivalent to calling Fseek (Stream,0,seek_set).
return value
Example Reference fseek ()

25.SETBUF (Sets the buffer area of the file stream)
Correlation function Setbuffer,setlinebuf,setvbuf
Table header file #include <stdio.h>
Defines the function void Setbuf (FILE * Stream,char * buf);
The function description calls Setbuf () to set the buffer for the file stream after the file stream is opened and before the content is read. The parameter stream is the specified file stream, and the parameter buf points to the custom buffer start address. If the parameter buf is a null pointer, it is unbuffered io. Setbuf () equivalent to call: Setvbuf (Stream,buf,buf?_iofbf:_ionbf,bufsiz)
return value
 
26.setbuffer (sets the buffer area of the file stream)
Correlation function Setlinebuf,setbuf,setvbuf
Table header file #include <stdio.h>
Defines the function void SetBuffer (FILE * Stream,char * buf,size_t size);
The function description calls SetBuffer () to set the buffer for the file stream after the file stream is opened and before the content is read. The parameter stream is the specified file stream, and the parameter buf points to the custom buffer start address, and the parameter size is the buffer.
return value

27.setlinebuf (set file stream to linear buffer)
Correlation function Setbuffer,setbuf,setvbuf
Table header file #include <stdio.h>
Defines the function void Setlinebuf (FILE * stream);
The function Description Setlinebuf () is used to set the unbuffered IO on which the file stream is to be changed. Equivalent to call: Setvbuf (Stream, (char *) null,_iolbf,0); refer to Setvbuf ().
return value

28.setvbuf (sets the buffer area of the file stream)
Correlation function Setbuffer,setlinebuf,setbuf
Table header file #include <stdio.h>
Defines the function int setvbuf (FILE * Stream,char * buf,int mode,size_t size);
The function description calls Setvbuf () to set the buffer for the file stream after the file stream is opened and before the content is read. The parameter stream is the specified file stream, the parameter buf points to the custom buffer start address, the parameter size is the buffer, and the parameter mode has the following
_IONBF Non-buffered IO
_IOLBF non-buffered IO based on change behavior
_IOFBF completely unbuffered io. If the parameter buf is a null pointer, it is unbuffered io.
return value

29.ungetc (writes the specified character back to the file stream)
Correlation function Fputc,getchar,getc
Table header file #include <stdio.h>
Defines the function int ungetc (int c,file * stream);
The function Description Ungetc () writes the parameter C character back to the file stream specified by the parameter stream. This writeback character is obtained by the next function that reads the file stream.
The return value returns the C character if successful, and EOF if there is an error.

Copy CodeThe code is as follows:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE *FP = NULL;
char* str;
char re;
int num = 10;
str = (char*) malloc (100);
snprintf (str, ten, "Test:%s", "0123456789012345678");
printf ("str=%s\n", str);
fp = fopen ("/local/test.c", "A +");
if (fp==null) {
printf ("Fail to open file\n");
}
Fseek (Fp,-1,seek_end);
num = Ftell (FP);
printf ("Test file long:%d\n", num);
FSCANF (FP, "%s", str);
printf ("str =%s\n", str);
printf ("Test A:%s\n", str);
while ((RE=GETC (FP))!=eof) {//getc can be used as a fgetc
printf ("%c", re);
}
Fread (STR,10,10,FP);
Fgets (STR,100,FP);
printf ("Test A:%s\n", str);
sprintf (str, "Xiewei test is:%s", "Abcdefghigkmni");
printf ("str2=%s\n", str);
fprintf (FP, "%s\n", str);
Fwrite (STR,2,10,FP);
num = Ftell (FP);
if (str!=null) {
Free (str);
}
Fclose (FP);
return 0;
}

C Language File Operation function Daquan (super verbose)

Related Article

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.