File Operations in C Language

Source: Internet
Author: User
Tags fread rewind


13.1c language file
1. Two file access methods (input and output)
Sequential access
Direct Access
2. Two data storage formats
Text Files
Binary files 13.2 file pointer
The general format of defining file type pointer variables:
File * pointer variable name;
For example:
File * Fp 1 ,* Fp 2; 13.3 open a file
Before using a file, open the file. Use the fopen function in C to open the file. The format is:
Fopen (file name, File Usage );
This function returns a pointer to the file type. For example:
File * Fp ;
Fp = Fopen ("file_1", "R ");
If the call is successful, Fp Point to file_1. Otherwise, null is returned. To ensure correct use of the file, test the file. Use the following statement:
If (( Fp = Fopen ("file_1", "R") = NULL)
{
Printf ("cannot open this file \ n ");
Exit (0 );
}
The most common file usage and its meaning are as follows:
1. "R". Open the text file for reading. (an error occurs if the file does not exist)
2. "rb". Open the binary file for reading.
3, "W". Open the text file for writing. (If the file does not exist, create a file. Otherwise, write the file from the start position, and the original content will be overwritten)
4. "WB". Open the binary file for writing.
5. "A". Open the text file to add data to the end of the file. (If the file does not exist, create the file. Otherwise, append the file after the original file)
6. "AB". Open a binary file to add data after the file.
The most common file usage and its meaning are as follows:
7. "R +". Open a text file for reading and writing. (when reading data, start from scratch. When writing data, new data only covers the occupied space, and remains unchanged afterwards)
8. "RB +". Open the binary file for reading and writing. The starting position of reading and writing can be set by the location function during subsequent read and write operations.
9. "W +". Create a new file and perform the write operation. Then, read the file from the beginning. (If the file exists, all the original content will disappear)
10, "WB +". The function is the same as "W +". In subsequent read and write operations, you can set the start position of read and write operations by the location function.
The most common file usage and its meaning are as follows:
11. "A +". The function is the same as "a". After adding new data to the end of the file, you can read the data from the beginning.
12. The function of "AB +" is the same as that of "A +". After adding new data to the end of the file, you can set the start position for reading by the location function. 13.4 close a file After reading and writing a file, use the fclose function to close the file. The format is as follows:
Fclose (File pointer)
For example, fclose ( Fp );
13.5 call the GETC (fgetc) and putc (fputc) functions for Input and Output
1. Call the putc (or fputc) function to output a character.
The call form is:
Putc (CH, Fp );
Function: Write the CH character to the file pointer. Fp In the specified file. when the output is successful, the putc function returns the output character. Otherwise, an EOF value is returned. EOF is in stdio. the symbolic constant defined in the H library function file. Its value is-1. 13.5 call the GETC (fgetc) and putc (fputc) functions for Input and Output
For example, output the text entered from the keyboard to the file named file_1.dat as is, and use the character @ as the keyboard input end sign.
# Include
Void main ()
{
File * fpout;
Char ch;
If (fpout = fpopen ("file_1", "W") = NULL)
{
Printf ("cannot open this file! \ N ");
Exit (0 );
}
Ch = getchar ();
While (Ch! = '@')
{Fputc (CH, fpout); CH = getchar ();}
Fclose (fpout );
}
2. Call the GETC (or fgetc) function to input a character.
The call form is:
Ch = GETC (PF );
Function: Read a character from a file specified by PF and return it as a function value.
For example, output the content in a file_1.dat text file on an existing disk to the terminal screen as is.
# Include
Void main (){
File * fpin;
Char ch;
If (fpin = fopen ("file_1.dat", "R") = NULL)
{Printf ("cann' t open this file! \ N "); exit (0 );}
Ch = fgetc (fpin );
While (Ch! = EOF)
{Putchar (CH); CH = fgetc (fpin );}
Fclose (fpin );
}
13.6 determine the end of a file function feof
EOF can be used as the end sign of a text file, but cannot be used as the end character of a binary file. feof can be used to determine both binary files and text files.
Example: Write Program To copy a text file (source) to another file (destination). The source file name and destination file name are input by the command line. The command format is as follows:
Executable program name source file name destination file name
# Include
Void filecopy (File *, file *);
Void main (INT argc, char * argv []) {
File * fpin, * fpout;
If (argc = 3)
{Fpin = fopen (argv [1], "R ");
Fpout = fopen (argv [2], "W ");
Filecopy (fpin, fpout );
Fclose (fpin); fclose (fpout );
}
Else if (argc> 3)
Printf ("the file names too success !! \ N ";
Else
Printf ("there are no file names for input or output !! \ N );
}
Void filecopy (File * fpin, file * fpout)
{
Char ch;
Ch = GETC (fpin );
While (! Feof (fpin ))
{Putc (CH, fpout); CH = GETC (fpin );}
}
13.7fscanf and fprintf
1. fscanf Function
Fscanf can only be input in a format from a text file, similar to the scanf function, except that the input object is data in the text file on the disk. The call form is:
Fscanf (File pointer, format control string, input item table)
For example, fscanf ( Fp , "% D", & A, & B );
Fscanf (stdin, "% d", & A, & B );
It is equivalent to scanf ("% d", & A, & B );
3. fprintf Function
The fprintf function converts data in the memory into corresponding characters in the format and uses ASCII Code The. fprintf function and the printf function are similar in the form of output to a text file, but the output content is stored in the text file on the disk in the format. The call form is as follows:
Fprintf (File pointer, format control string, output item table)
For example, fprintf ( Fp , "% D", x, y );
The following statement fprintf (stdout, "% d", x, y)
13.8fgets and fputs Functions
1. fgets Function
The fgets function is used to read strings from files. The call form is as follows:
Fgets (STR, n, Fp );
Function function: From Fp The specified file contains n-1 characters in the space where STR is the starting address. If n-1 characters are not fully read, a line break or an EOF is used to end the read operation, STR is returned as the function value.
13.8fgets and fputs Functions
2. fputs Function
The fput function outputs a string to a file. The function call form is as follows:
Fputs (STR, Fp );
Note: To facilitate reading, when outputting a string, you must manually add a string such as "\ n.13.9fread and fwrite Functions
Fread and fwrite functions are used to read and write binary files. Their calling forms are as follows:
Fread (buffer, size, count, Fp );
Fwrite (buffer, size, count, Fp );
Buffer: the first address of the data block to be input or output.
Count: the number of input or output data blocks per read/write.
Size: the number of bytes per data block.
Fp : File pointer
13.9fread and fwrite Functions
For example, the following struct is available:
Struct st {
Char num [8];
Float MK [5];
} Pers [30];
The following cycle outputs the data from these 30 elements Fp In the specified file.
For (I = 0; I <30; I ++)
Fwrite (& pers [I], sizeof (struct st), 1, Fp );
13.9fread and fwrite Functions
The following statement Fp Each student data is read into the pers array one by one.
I = 0;
Fread (& pers [I], sizeof (struct st), 1, Fp );
While (! Feof (Fp ))
{I ++;
Fread (& pers [I], sizeof (struct st), 1, Fp );
}
13.10 file locating Functions
1, Fseek Function
Fseek The function is used to move the file position pointer to the specified position. The subsequent read or write operations start from this position. The function is called as follows:
Fseek (PF, offset, origin)
PF: file pointer
Offset: the displacement in bytes, which is a long integer.
Origin: it is the starting point, used to specify the position of the displacement as the benchmark.
1, Fseek Function
Expression of displacement
The starting point of the identifier number.
Seek_set 0 file starts
Seek_end 2. End of the file
Current location of seek_cur 1 file
If pf already points to a binary file;
Fseek (PF, 3 0l , Seek_set)
Fseek (PF,-10l * Sizeof (INT ), Seek_end )
For text files, the displacement must be 0. For example:
Fseek (PF, 0l , Seek_set)
Fseek (PF, 0l , Seek_end )
2. ftell Function
The ftell function is used to obtain the position of the pointer to the current position of the file. The function provides the number of bytes of the pointer to the beginning of the file. For example;
Long T;
T = ftell (PF );
When a function call error occurs, the function returns-1l.
We can test the length of a file in the following ways:
Fseek ( Fp , 0l , Seek_end );
T = ftell ( Fp );
3. Rewind Function
The call form is:
Rewind (PF );
The function does not return values. The function is used to return the position pointer of a file to the beginning of the file.
13.10 file application
There are 10 positive integers not less than 2 in the test.txt file on the example, and the program is compiled by function call. The requirements are as follows:
1. In the called function Prime, judge and count the prime number and number of the 10 integers.
2. Add the full element number to the end of the test.txt file in the master node and output it to the screen.
# Include
# Include
Int prime (int A [], int N)
{
Int I, j, k = 0, flag = 0;
For (I = 0; I {for (j = 2; j if (a [I] % J = 0)
{Flag = 0; break ;}
Else flag = 1;
If (FLAG)
{A [k] = A [I]; k ++ ;}
}
Return K;
}
Void main (){
Int N, I, a [10];
File *Fp ;
Fp = Fopen ("test1-2.txt", "R + ");
For (n = 0; n <10; n ++)
Fscanf ( Fp , "% D", & A [n]);
N = prime (A, N );
Fseek ( Fp , O, 2 );
For (I = 0; I {printf ("% 3d", a [I]);
Fprintf ( Fp , "% 3d", a [I]);
}
Fclose ( Fp );
}


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.