Related Operations for C language (vii) files

Source: Internet
Author: User
Tags file copy

Reprint please indicate source: http://blog.csdn.net/u011974987/article/details/52354074
This article is from: "Xuhao's Blog"

opening and closing of C language files

In the C language, the file operation is done by the library function, we will summarize the file related operations.

Opening of the file (fopen function)

The fopen () function is used to open a file whose format is:

FILE *fopen(charchar *type);

FileName is file name (including file path), type is open, and they are all strings. fopen () Gets the file information, including the filename, file status, current read and write location, and saves the information to a struct variable of the file type, and then returns the address of the variable.

If you receive the return value of fopen (), you need to define a pointer to the FILE type. For example:

*fp = ("demo.txt""r");

Above is the "read-only" way to open the Demo.txt file in the current directory, and the FP point to the file, so that the FP to operate the demo.txt. FP is often referred to as a file pointer. Another example:

*fp = fopen("D:\\demo.txt","rb");

Represents the binary opening of the Demo.txt file under the D drive, allowing both read and write.

There are several modes of opening (mode):

meaning of using file means
"R" (read-only) opens a text file for input
"W" (write-only) opens a text file for the output
"A" (append) opens a text file for append
"RB" (read-only) open a binary file for input
"WB" (write only) open a binary file for output
"AB" (append) opens a binary file for append
"r+" (read/write) open a text file for read/write
"w+" (read/write) create a text file for read/write
"A +" (read/write) open a text file for read/write
"rb+" (read/write) open a binary file for read/write
"wb+" (read/write) create a binary file for read/write
"ab+" (read/write) open a binary file for read/write

When a file is opened, fopen will return a null pointer value NULL if an error occurs, so we can handle this in the program

if( (fp=fopen("D:\\demo.txt","rb") == NULL ){    printf("open file is error D:\\demo.txt file!");    getchar();    exit(1);}

If you open the file again, the returned pointer is empty, it means that you cannot open the Demo.txt file in the D drive with the directory, and the error message of the output prompt!! printf ("Open file is Error D:\demo.txt file!");

file Close (fclose function)

FP is a file pointer. For example:

fclose(fp);

When the file is closed gracefully, the return value of fclose () is 0, and if a non-0 value is returned, it indicates an error occurred.

the difference between a text file and a binary file in C

The following excerpt from the online:

From the file encoding method, the file can be divided into ASCII code files and binary code file two kinds.

ASCII files are also referred to as text files, which are stored on disk with one byte per character for the corresponding ASCII code. For example, the number 5678 is stored in the following form:
ASC code: 00110101 00110110 00110111 00111000
↓↓↓↓
Decimal code: 5 6 7 8 A total of 4 bytes. ASCII files can be displayed on the screen by characters, such as the source program file is an ASCII file, with the DOS command type to display the contents of the file. Because it is displayed by character, it can read the contents of the file.

Binary files are stored as binary encoding methods for storing files. For example, the number 5678 is stored in the form: 00010110 00101110 is only two bytes. Binary files can also be displayed on the screen, but their contents are unreadable. When processing these files, the C system does not distinguish between types, which are treated as character streams and processed in bytes. The start and end of a stream of input and output characters is controlled only by program control and not by physical symbols such as carriage returns. Therefore, this file is also referred to as a "streaming file".
A file can be opened in text or binary mode, where the difference is that the carriage return is treated as a character '/n ' in text mode, while the binary mode considers it to be two characters 0x0d,0x0a; if you read 0x1b in a file, the text pattern will consider it a file terminator, That is, the binary model does not process the file, and the text is converted to the data in a certain way.

c languages Read and write files in character form

When you read or write a file as a character, you can read one character from the file at a time, or write a character to the file. The main use of two functions: Fgetc () and FPUTC ().

character reading function fgetc

FGETC is the abbreviation for file get char, which means that a character is read from the specified file. Its prototype is:

int*fp);

FP is a file pointer. FGETC () returns the read-to character when it is successfully read, reads to the end of the file, or returns EOF when the read fails.

EOF is the abbreviation for end of file, which represents the end of the document, is the macro defined in Stdio.h, and its value is a negative number, which is often-1. The return value type is int to accommodate this negative number (char cannot be negative).

EOF is not an absolute-1 or another negative number, which depends on the implementation of the compiler.

FGETC () Use example:

char ch;FILE *fp = fopen("D:\\demo.txt""r+");ch = fgetc(fp);

Indicates that a character is read from the D:\demo.txt file and saved in the variable ch.

There is a position pointer inside the file that points to the current read-write location, that is, to read and write to the first few bytes. When the file is opened, the pointer always points to the first byte of the file. With the FGETC function, the pointer moves backwards by one byte, so you can read multiple characters using fgetc several times in a row.

Note: The position pointer inside this file is not the same as the pointer in C language. The position pointer is just a flag indicating where the file reads and writes to, that is, the number of bytes read and write, which does not represent an address. Once a file is read and written, the position pointer moves once, and it does not require you to define and assign a value in the program, but is set automatically by the system and is transparent to the user.

Instance:

#include <stdio.h>intMain () {FILE *fp;CharCh//If the file does not exist, give a hint and exit    if((Fp=fopen ("D:\\demo.txt","RT")) = = NULL) {printf("Cannot open file, press any key to exit!"); Getch ();Exit(1); }//read one byte at a time until the read is complete     while((CH=FGETC (fp))! = EOF) {Putchar(CH); }Putchar(' \ n ');//Output line breakFclose (FP);return 0;}

Create a Demo.txt file under D, enter any content and save, run the program, and you will see that the content you just entered is all displayed on the screen.

The function of the program is to read the characters from the file and display them on the screen until the reading is complete.

The 14th line of the program is critical, while the condition for the while loop is (CH=FGETC (fp))! = EOF. Fget () reads one character at a time from the position pointer and saves it to the variable ch, and the position pointer moves backwards by one byte. When the file pointer moves to the end of the file, Fget () cannot read the character, and then returns EOF, indicating that the file read is finished.

a description of the EOF

EOF originally represents the end of the file, which means that the read is finished, but many functions also return EOF when reading an error, so when the EOF is returned, is the file read or read error? We can judge by the two functions in stdio.h, namely feof () and ferror ().

The feof () function is used to determine whether the internal pointer of the file points to the end of the file, and its prototype is:

intfeof ( FILE * fp );

Returns a value other than 0 when pointing to the end of the file, otherwise 0 is returned.

The Ferror () function is used to determine whether a file operation is wrong, and its prototype is:

int*fp );

A value other than 0 is returned when an error occurs, otherwise 0 is returned.

It is important to note that file errors are very rare cases where the above example basically guarantees that the data in the file is read. If the pursuit of perfection, you can also add a judgment and give hints:

#include <stdio.h>intMain () {FILE *fp;CharCh//If the file does not exist, give a hint and exit    if((Fp=fopen ("D:\\demo.txt","RT")) = = NULL) {printf("Cannot open file, press any key to exit!"); Getch ();Exit(1); }//read one byte at a time until the read is complete     while((CH=FGETC (fp))! = EOF) {Putchar(CH); }Putchar(' \ n ');//Output line break    if(Ferror (FP)) {puts("Read error"); }Else{puts("Read succeeded"); } fclose (FP);return 0;}

In this way, whether it is error or normal reading, you can have a good idea.

Character Write function Fputc

FPUTC is file output char, meaning that a character is written to the specified file. The invocation is in the form:

intint*fp );

CH is the character to be written, and the FP is the file pointer. FPUTC () writes the written character when the write succeeds, returns EOF on failure, and returns a value of type int to accommodate this negative number. For example:

fputc(‘a‘, fp);

Or

char‘a‘;fputc(ch, fp);

Indicates that the character ' A ' is written to the file pointed to by the FP.

Two-point description:

1) The file being written can be opened with write, read/write, append, or write or read/write to open an existing file, the original file content will be purged and the written characters will be placed at the beginning of the file. If you want to keep the contents of the original file and put the written characters at the end of the file, you must open the file in Append mode. The file is created if it does not exist, regardless of the way it is opened.

2) Each write one character, the inside position of the file pointer moves backwards one byte.

#include <stdio.h>intMain () {FILE *fp;CharCh//Determine if the file opened successfully    if((Fp=fopen ("D:\\demo.txt","wt+")) = = NULL) {printf("Cannot open file, press any key to exit!\n"); Getch ();Exit(1); }printf("Input a string:\n");//read one character at a time from the keyboard and write to the file     while((Ch=getchar ())! =' \ n ') {FPUTC (CH,FP); } fclose (FP);return 0;}

Run the program, enter a line of characters and press ENTER to end, open the D disk under the Demo.txt file, you can see what you just entered.

c languages Read and write files in string form

The above module fgetc () and the FPUTC () function can read and write only one character at a time, and it is slower to read and write a string or a block of data each time in the actual process, which can significantly improve the efficiency.

Read String function fgets

The fgets () function is used to read a string from the specified file and save it to a character array, which is prototyped as:

charchar *strint n, FILE *fp );

STR is an array of characters, N is the number of characters to read, and the FP is a file pointer.
return Value: returns the first address of a character array when read succeeds, or STR; returns NULL if the read fails, or null if the internal pointer to the file already points to the end of the file at the start of the read.

The string that is read automatically adds '% ' at the end, and n characters also include ' + '. That is, only n-1 characters are actually read, and if you want to read 100 characters, the value of n should be 101. For example:

#define N 101charstr[N];FILE *fp = fopen("D:\\demo.txt""r");fgets(str, N, fp);

Represents a 100 character read from D:\demo.txt and is saved to the character array str.

It is important to note that if a newline occurs before the n-1 characters are read, or if the end of the file is read, the read ends. This means that no matter how large the value of n is, fgets () can read at most one row of data, not across rows. In the C language, there is no function to read the file by line, we can use Fgets () to set the value of N to be large enough to read a row of data at a time.

A line of read files, the code is as follows:

#include <stdio.h>#include <stdlib.h>#define NintMain () {FILE*FP; Char str[n+1];if((Fp=fopen ("D:\\demo.txt","RT")) = = NULL) {printf("Cannot open file, press any key to exit!\n"); Getch ();Exit(1); } while(Fgets (str, N, fp)! = NULL) {printf('%s', str); } fclose (FP);system("Pause");return 0;}

In this D:\demo.txt: file, write the following:

My Name is Android
Google

Then compile and run the above program, the result is:

My Name is Android Google 请按任意键继续...
Write String function fputs

The fputs function refers to a file in which a string is written, and its prototype is:

int  fputs(char *str,FILE *fp);

STR is the string to be written, the FP is the file pointer, the write successfully returns a non-negative number, and the failure returns EOF.
eg

char *str"xuhao";FILE *fp = fopen("D:\\demo.text","a+");

Indicates that the string str is written to the D:\demo.txt file.

Append a string to the D:\demo.txt file created in the preceding code.

#include <stdio.h>intMain () {FILE *fp;Charstr[102] = {0}, strtemp[ -];if((Fp=fopen ("D:\\demo.txt","at+")) = = NULL) {printf("Cannot open file, press any key to exit!\n"); Getch ();Exit(1); }printf("Input A string:"); Gets (strtemp);strcat(STR,"\ n");strcat(str, strtemp);fputs(str, FP); Fclose (FP);return 0;}

Compile and run the program, enter Java C + + in the pop-up view, open D:\demo.txt, and the file contents are:

is
operation of other files in C language

such as file copy, the code is as follows:

void Main () {Char*read_path="E:\\dongnao\\vip\\ndk\\08_08_c_05\\files\\liuyan.png"; Char*write_path="E:\\dongnao\\vip\\ndk\\08_08_c_05\\files\\liuyan_new.png";//Read File B-character denotes binary binary file operationFILE*READ_FP=fopen(Read_path,"RB");//write the fileFILE*WRITE_FP=fopen(Write_path,"WB");//Copy    intbuff[ -];//Buffer area    intLen =0;//Data length per read     while(len =fread(Buff, sizeof (int), -, READ_FP))! =0){//write the read to a new file        fwrite(Buff,sizeof (int), LEN,WRITE_FP); }//Close stream    fclose(READ_FP);fclose(WRITE_FP); GetChar ();}
//获取文件的大小void main(){    char"E:\\dongnao\\vip\\ndk\\08_08_C_05\\files\\liuyan.png";    "r");    //重新定位文件指针    //SEEK_END文件末尾,0偏移量    fseek(fp,0,SEEK_END);    //返回当前的文件指针,相对于文件开头的位移量    long filesize = ftell(fp);    printf("%d\n",filesize);    getchar();}

Commonly used file operations are the above several, about the file encryption and decryption, binary file encryption and decryption, may later be combined with the JNI call and the NDK development and implementation, well, this article ends!

More series related articles Portal:

C Language (i) Basic data types
C Language (ii) the understanding of signed numbers and unsigned numbers
C Language (iii) string processing functions
C Language (iv) understanding of the concept of pointers
C language (v) allocation and release of memory
C language (VI) Structure and consortium

Learn to understand and organize your notes.
I hope you can advise or make valuable comments, thank you! Study together.
Reprint Please specify source: http://blog.csdn.net/u011974987/article/details/52305364
Personal site: Xuhao.tech

Related Operations for C language (vii) files

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.