C Language File Operation function Daquan

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

fopen (Open file)
Correlation function Open. Fclose
Table header file #include <stdio.h>
Defines the function FILE * fopen (const char * path,const char * mode);
The function description path string includes the file path and file name to open, and the parameter mode string represents the flow pattern.
Mode has the following pattern strings:
R opens a read-only file, and the file must exist.
r+ open a writable file, the file must exist.


W Open the file only, 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 readable and writable files. If the file exists, the file length is cleared to zero, that is, the file content disappears. If the file does not exist, the file is created.
A opens the file only in an additional way.

If the file does not exist, it will be created, assuming that the file exists, the data written will be added to the end of the file, that is, the original contents of the file will be retained.


A + opens readable and writable files in an additional way. If the file does not exist. The file is created. Assume that the file exists. The written data is added to the end of the file, i.e. the original contents of the file are retained.
Copy the code code such as the following:
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 a combination of RB, w+b, or ab+. The b character is added to tell the library that the file opened is a binary file, not a plain text file. This character is ignored only in POSIX systems, including Linux. A new file created by fopen () will have a s_irusr| s_iwusr| s_irgrp| s_iwgrp| s_iroth| S_iwoth (0666) permissions. This file permission also participates in the Umask value.


After the return value file is opened successfully. The file pointer to the stream is returned.

Returns null if File open fails. and the error code exists in the errno.


Additional instructions generally. After opening the file will make some file read or write action, if the file failed to open, the next read and write action can not be carried out smoothly. Therefore, after fopen (), please make the wrong inference and processing.
Example
to copy code code such as the following:
#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
header file: #include <stdio.h>
function prototype: int fprintf (file *stream, Char *format[, argument,...]);
file* A FILE-type pointer
char* format the input function, as in printf,
return value: The number of bytes converted when successful. A negative number is returned on failure
FP = fopen ("/local/test.c", "A +");
fprintf (FP, "%s\n", str);


2. fscanf
Function: Run formatted input
header file from a stream: #include <stdio.h>
function prototype: int fscanf (FILE *stream, char * Format[,argument ...]);
file* A FILE-type pointer
char* format the output function. The same as the format in scanf
return value: The number of bytes converted when successful. A negative number is returned on failure
FP = fopen ("/local/test.c", "A +");
FSCANF (FP, "%s", str);


3. clearerr (clear file stream error flag)
Related function feof
header file #include <stdio.h>
define function void Clearerr (file * stream) ; The
Function Description Clearerr () Clears the error flag used by the file stream specified by the stream.


return value

4.fclose (close file)
related function Close,fflush. fopen Setbuf
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, or EOF when an error occurs and saves the error code to errno. The
Error code EBADF indicates that the parameter stream is not an open file. For the
example, refer to fopen ().

5.fdopen (convert file descriptive narrative to file pointer)
Related function fopen,open,fclose
header file #include <stdio.h>
Define function file * Fdopen ( int fildes,const char * mode); The
Function Description Fdopen () Converts the file descriptive narrative of the reference 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 description of the narrative word read and write mode. For the mode string format please refer to fopen (). The
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 code code such as the following:
#include <stdio.h>
Main ()
{
FILE * fp =fdopen (0, "w+");
fprintf (FP, "%s/n", "hello!");
Fclose (FP);
}
Run hello!


6.feof (check that the file stream is read to the end of the file)
related function 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. The mantissa stream is the file pointer returned by fopen (). It is assumed that a value other than 0 is returned to the end of the file, and 0 is returned. The
return value returns a non-0 value that represents the end of the file reached.


 
7.fflush (update buffer)
Correlation function Write,fopen,fclose,setbuf
Table 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 Count stream.

Assuming that the parameter stream is Null,fflush () updates all open file data.
The return value returned successfully to 0. Failed to return EOF. The error code is stored in the errno.
Error code EBADF the file specified by stream was not opened, or opened with a status of just read. Other error codes refer to write ().
 
8.FGETC (read one character from the file)
Correlation function Open,fread,fscanf,getc
Table header File include<stdio.h>
Defines the function NT fgetc (FILE * stream);
Function Description fgetc () reads a character from the file referred to by stream. 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 the code code such as the following:
#include <stdio.h>
Main ()
{
FILE *FP;
int C;
Fp=fopen ("exist", "R");
while ((C=FGETC (FP))!=eof)
printf ("%c", c);
Fclose (FP);
}


9.fgets (read 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 in the file referred to by the reference stream to the memory space referred to by the reference 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 the code code such as the following:
#include <stdio.h>
Main ()
{
Char s[80];
Fputs (Fgets (S,80,stdin), stdout);
}
Run this is a test/* input */
This is a test/* output */


10.fileno (the file descriptive narrative used to return 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 descriptive narrative used by the file stream specified by the stream.
The return value returns a descriptive description of the file.
Example
Copy the code code such as the following:
#include <stdio.h>
Main ()
{
FILE * FP;
int FD;
Fp=fopen ("/etc/passwd", "R");
Fd=fileno (FP);
printf ("fd=%d/n", FD);
Fclose (FP);
}
Run 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 and write to the file specified by the parameter stream.


The return value FPUTC () returns the character that was successfully written, that is, the number of parameters. Returning EOF indicates a write failure.


Example
Copy the code code such as the following:
#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 referred to by the reference s to the file referred to in 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, please 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. The parameter ptr points to the data space that you want to store the read in. The number of characters read is determined by the number of parameters size*nmemb. Fread () returns the number of Nmemb actually read, assuming that this value is smaller than the number of references Nmemb. The representative may have read the end of the file or an error has occurred, it is necessary to use feof () or ferror () to determine what happens.
The return value returns the number of Nmemb actually read.
Additional Instructions
Example
Copy the code code such as the following:
#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);
}
Run
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 The path string includes the file paths and file names you want to open, and the number of references is in 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 that references path.


When the return value file is opened successfully, the file pointer to the stream is returned.

Assuming the file open fails, it returns null and the error code exists in errno.


Example
Copy the code code such as the following:
#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. The parameter offset is the number of displacements that move the read-write position based on the whence.
The number of whence is one of the following:
Seek_set the offset offset from the beginning of the file to the new read-write location. Seek_cur adds offset displacement to the current read and write position.
Seek_end points The read-write position to the end of the file and then adds offset offset.
When the whence value is Seek_cur or seek_end, the parameter offset agrees to the occurrence of a negative value.
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 to the current read and write locations.
Example
Copy the code code such as the following:
#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);
}
Run 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 if there is an error. The errno will store the error code.
The error code EBADF the stream of invalid or movable read and write locations.
Example 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. The number of characters written in total is determined by the number of parameters size*nmemb.

Fwrite () returns the number of Nmemb actually written.
The return value returns the number of Nmemb actually written.


Example
Copy the code code such as the following:
#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);
}
Run the references 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 by the 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 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. Instead, the GETC (STDIN) macro is defined.
Example
Copy the code code such as the following:
#include <stdio.h>
Main ()
{
FILE * FP;
int c,i;
for (i=0li<5;i++)
{
C=getchar ();
Putchar (c);
}
}
Run 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 reference 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. Returning NULL indicates an error occurred.


Additional instructions because the get () cannot know the size of the string s, it must encounter newline characters or end of file before ending the input, so easy causes a security problem with buffer overflow. It is recommended to use Fgets () instead.


Example 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 name of the file referred to in the reference template is called the last six characters in the string 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. Assuming the file open fails, it returns null and the error code exists in errno.
Additional Description The filename string referred to by the template must be declared as an array, such as:
Char template[]= "template-xxxxxx".
Do not use char * template= "template-xxxxxx";
Example
Copy the code code such as the following:
#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 specified file to the parameter stream. Although PUTC () works the same as FPUTC (). But PUTC () is defined as a macro, not a real function call.


The return value PUTC () returns the character that was successfully written, that is, the number of parameters.

Returning EOF indicates a write failure.
Example 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 characters to the standard output device.
The return value Putchar () returns the successful output character, which is the 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 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 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);
Function description After opening the file stream. Call Setbuf () to set the buffer for the file stream before reading the content.

The parameter stream is the specified file stream, and the BUF points to the custom buffer start address. Assume that the parameter buf is a null pointer. 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);
Function description After opening the file stream. Before the content is read. Call SetBuffer () to set the buffer for the file stream.

The argument stream is the specified file stream, and the number of arguments buf points to the custom buffer start address, and the 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 non-buffered IO that the file stream is based on. Equivalent to call: Setvbuf (Stream, (char *) null,_iolbf,0); see 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);
Function description After opening the file stream. Call Setvbuf () to set the buffer for the file stream before reading the content.

The argument stream is the specified file stream, and the number of arguments buf points to the custom buffer start address, the size of which is the buffer, and the number of parameters in mode
_IONBF Non-buffered IO
_IOLBF non-buffered IO based on change behavior
_IOFBF completely unbuffered io.

Assume that the parameter buf is a null pointer. 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 count 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 the code code such as the following:
#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 manipulation functions Daquan

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.