A program that modifies the specified content in a file.
The following is a program for modifying the specified content in a file. The following functions are mainly used:
FILE * fopen (const char * path, const char * mode );
Size_t fread (void * buffer, size_t size, size_t count, FILE * stream );
Buffer: the memory address used to receive data;
Size: the size of each data item to be read, in bytes;
Count: the number of data items to read;
Stream: input stream.
Size_t fwrite (const void * buffer, size_t size, size_t count, FILE * stream );
Int fseek (FILE * stream, long offset, int fromwhere );
The function sets the position of the file pointer stream. If the execution is successful, stream points to fromwhere (starting position of the Offset: File Header 0 (SEEK_SET), current position 1 (SEEK_CUR), and end 2 (SEEK_END) as the benchmark, offset (pointer offset. If the execution fails (for example, the offset value exceeds the file size), the position pointed to by the stream is not changed.
The program code is as follows:
# Include
# Include
# Include
# Include
Int main ()
{
Time_t starttime = time (NULL );
FILE * fd;
Fd = fopen ("/file2.txt", "r + ");
If (fd = NULL)
{
Printf ("fail open file1.txt \ n ");
Return-1;
}
// The following part is the Write File
/* Int I = 0;
Int j = 0;
For (I = 0; I <1310720; ++ I)
{
Char buf [11] = "0123456789 ";
Fwrite (buf, sizeof (buf), 1, fd );
}*/
// The following part modifies the specified content
Char;
Int count = 0;
While (fread (& a, sizeof (char), 1L, fd) = 1)
{
If (a = '9 ')
{
A = '1 ';
Fseek (fd,-sizeof (char), SEEK_CUR );
Fseek (fd, 0L, SEEK_CUR );
Fwrite (& a, sizeof (char), 1L, fd );
If (655360 = count ++)
Break;
}
}
Time_t endtime = time (NULL );
Printf ("time = % g \ n", endtime-starttime );
}