C Language File Operation function Daquan (super verbose)

Source: Internet
Author: User
Tags define function fread rewind
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.



r      Open text fileforreading.  The stream is positioned at the beginning of the file.

r+     Openforreading and writing.  The stream is positioned at the beginning of the file.

w      Truncate file to zero length or create text fileforwriting.  The stream is positioned at the beginning of the file.

w+     Openforreading and writing.  The file is createdifit does not 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 createdifit does not exist.  The stream is positioned at the

       end of the file.

a+     Openforreading and appending (writing at end of file).  The file is createdifit does not exist.  The initial file posi‐

       tionforreading is at the beginning of the file, but output is 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


#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

#include<stdio.h>

Main()

{

FILE * fp =fdopen(0,"w+");

Fprintf(fp,"%s/n","hello!");

Fclose(fp);

}

Execute hello!


6.feof (check if the file stream reads the end of the file)
Correlation function Fopen,fgetc,fgets,fread
Table 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)
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 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 (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 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


#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


#include<stdio.h>

Main()

{

Char s[80];

Fputs(fgets(s,80,stdin),stdout);

}

Execute this is a test /* enter */

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


#include<stdio.h>

Main()

{

FILE * fp;

Int fd;

Fp=fopen("/etc/passwd","r");

Fd=fileno(fp);

Printf("fd=%d/n",fd);

Fclose(fp);

}

Execute 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


#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)
Related function fopen,fwrite,fscanf,fputc,putc
header file #include <stdio.h>
Define 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 returns the number of characters written out if successful, and the return EOF indicates an error occurred. For the
example, refer to Fgets ().
Fread (read data from file stream)
Related function fopen,fwrite,fseek,fscanf
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 Description
Example


#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);

}

执行

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


#include<stdio.h>

main()

{

FILE * fp;

fp=fopen(“/etc/passwd”,”r”);

fp=freopen(“/etc/group”,”r”,fp);

fclose(fp);

}


15.fseek (move file stream read and write location)
Related function rewind,ftell,fgetpos,fsetpos,lseek
header file #include <stdio.h>
Define function int Fseek (FILE * stream,long offset,int whence); The
Function describes fseek () 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 is the new read and write location. The seek_cur increases the offset displacement by the current read and write position. The
Seek_end points the read-write position to the end of the file and increments the offset offset.
when the whence value is Seek_cur or seek_end, the parameter offset allows negative values to appear.
The following is a more specific way to use:
1) to move the read and 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); The
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


#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);

}

执行 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


#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);

}

执行 参考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


#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


#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.

#include <stdio.h>

#include <stdlib.h>

Int main()

{

      FILE *fp = NULL;

      Char* str;

      Char re;

      Int num = 10;

      Str = (char*)malloc(100);

      //snprintf(str, 10,"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 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;

}
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.