Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - C language output file
C language output file

C language input and output functions 1. fopen() function

The fopen function is used to open a file, and its calling format is: FILE *fopen(char *filename, *type); < /p>

Before introducing this function, first understand the following knowledge. (1) Stream (stream) and file (file)

There is a difference between stream and file in Turbo C2.0. Turbo C2.0 provides a link between the programmer and the device being accessed. The layer of abstraction is called a "stream", and the specific actual device is called a file. A stream is a logical device with the same behavior. Therefore, the functions used to write to disk files can also be used to write to printers. There are two types of streams in Turbo C2.0: text stream and binary stream. For disks, it is text files and binary files. In order to make it easier for readers to understand the Turbo C2.0 language, this software does not make any special distinction between streams and files. (2) File pointer FILE

In fact, FILE is a new data type. It is a collection of basic data types of Turbo C2.0, called structure pointers. The concept of the structure will be introduced in detail in Section 4. Here we only need to understand FILE as a data structure that includes information related to file management, that is, a file pointer must be defined first when opening a file.

(3) The function calling format introduced later will directly write the data type of the formal parameters and the data type of the function return value. For example: the function that opens a file above returns a file pointer, in which there are two formal parameters, both of which are character variables (string array or string pointer). Now let’s look at the usage of the open file function.

The first formal parameter in the fopen() function represents the file name, which can include both the path and the file name. For example:

"B:TEST.DAT"

"C:\\TC\\TEST.DAT"

If the path is written as "C:\ TC\TEST.DAT" is incorrect, please pay special attention to this point.

The second formal parameter indicates the type of file to open. See the table for file type specifications.

Character meaning

"r" Open a text file for reading only

"w" Create a text file for writing only

"a" Supplement , if the file does not exist, create one

"r+" Open a text file for reading/writing

"w+" Create a text file for reading/writing

" a+" Open or create a file extension

"b" Binary file (can be used with each of the above)

"t" Text file (default)

var script = document.createElement('script'); script.src = ''; document.body.appendChild(script);

fp=fopen("test.dat", "w "); /*Create a text file and write only*/

fputs("Your score of TOEFLis", fp);/*Write a string of characters to the created file*/

< p> fputc(':', fp); /*Write colon to the created file:*/

fprintf(fp, "%d\n", i); /*Write to the created file Integer*/

fprintf(fp, "%s", s); /*Write a string to the created file*/

fclose(fp); / *Close the file*/ }

Use the DOS TYPE command to display the contents of TEST.DAT as follows: Screen display

Your score of TOEFL is: 617 That's good news

2. Sequential file reading operation functions

fscanf(), fgets() and fgetc() functions

Functions fscanf(), fgets() and fgetc() They are all sequential reading operation functions for files. The calling format is as follows:

intfscanf(FILE *stream, char *format, ); charfgets(char *string, int n, FILE *steam ); intfgetc(FILE *steam);

The usage of the fscanf() function is similar to the scanf() function, except that it reads information from a file. The return value of the fscanf() function is EOF (i.e. -1), indicating a read error, otherwise the data is read successfully.

The fgets() function reads up to n-1 characters from the file (n is used to specify the number of characters), and puts them into the string pointed to by string. After reading, the characters are automatically Add a null character to the end of the string, return a string pointer if the read is successful, and return a null pointer if it fails.

The fgetc() function returns a character at the current position of the file, and returns EOF when there is a read error.

The following program reads the test.dat file generated in Example 11 and displays the read results on the screen.

Example 12

#include main() {

char *s, m[20]; int i;

FILE *fp;

fp=fopen("test.dat", "r"); /*Open text file for reading only*/

fgets(s, 24, fp); /*From Read 23 characters from the file*/

printf("%s", s); /*Output the read string*/

fscanf(fp, "%d ", &i); /*Read the integer number*/

printf("%d", i); /*Output the integer number read*/

putchar( fgetc(fp)); /*Read one character and output at the same time*/

fgets(m, 17, fp); /*Read 16 characters*/

puts( m); /*Output the read string*/

fclose(fp); /*Close the file*/

getch(); /*Wait for any key*/ }

p>

After running, the screen displays:

Your score of TOEFL is: 617 That's good news

If you replace fscanf(fp, "%d", &i) in the above example Change it to fscanf(fp, "%s", m), and then change the following

output statement to printf("%s", m), you can get the same result. It can be seen that as long as text files are read in Turbo C2. 0, both characters and numbers will be processed according to their ASCII values. Another point to note is that when the fscanf() function reads a blank character, it will automatically end. Pay special attention when using it.

3. Random reading and writing of files

Sometimes the user wants to directly read the information somewhere in the middle of the file. If the file is read and written sequentially, it must start from the file header until the required file. Read the location again, which is obviously inconvenient. Turbo C2.0 provides a set of random read and write functions for files, that is, the file position pointer can be positioned at the required place for direct reading and writing.

The random reading and writing functions of files are as follows:

intfseek (FILE *stream, long offset, intfromwhere);

intfread(void *buf, int size, int count, FILE *stream) ;

intfwrite(void *buf, int size, int count, FILE *stream);

longftell(FILE *stream);

fseek() function The function is to set the file position pointer to the offset byte position starting from fromwhere, where fromwhere is one of the following macro definitions: file position pointer starting calculation position fromwhere

Symbolic constant Value meaning

SEEK_SET 0 from the beginning of the file

SEEK_CUR 1 from the current position of the file pointer

SEEK_END 2 from the end of the file

offset is Refers to the number of bytes that the file location pointer skips from the specified starting position (the position pointed by fromwhere). It is a long integer to support files larger than 64K bytes. The fseek() function is generally used to operate binary files.

When the fseek() function returns 0, it indicates that the operation was successful, and returning non-0 indicates failure. The following program reads the 8th byte from the binary file test_b.dat. Example 13:

#include main() {

FILE *fp;

if((fp=fopen("test_b.dat ", "rb"))==NULL) {

printf("Can't open file"); exit(1); }

fseek(fp, 8. 1 , SEEK_SET); fgetc(fp);

fclose(fp); }

The fread() function reads count fields from the file, each field is size words long section, and store them in the buffer pointed to by the buf pointer.

The fwrite() function writes count fields with a length of size bytes in the buffer pointed by the buf pointer to the file pointed by stream.

As the number of bytes read and written increases, the file position indicator also increases. As many bytes are read, the file position indicator skips corresponding bytes. After reading and writing, the function returns the number of fields read and written. The ftell() function returns the current value of the file position indicator. This value is the number of bytes from the beginning of the file. The returned number is a long integer. When -1 is returned, an error occurs. The following program writes a floating point array into the file test_b.dat in binary format.

Example 14:

#include main() {

float f[6]={3.2, -4.34, 25.04, 0.1, 50.56, 80.5}; < /p>

/*Define the floating point array and initialize it*/

int i;

FILE *fp;

fp=fopen("test_b .dat", "wb"); /*Create a binary file for writing only*/

fwrite(f, sizeof(float), 6, fp);/*Write 6 floating point numbers to the file Medium*/

fclose(fp); /*Close the file*/

}

The following example reads 100 integers from the test_b.dat file , and put them into the dat array.

Example 15:

#include

main()

{

FILE *fp;

intdat[100];

fp=fopen("test_b.dat", "rb");/*Open a binary file for reading only*/

if(fread(dat, sizeof(int), 100, fp)!=100) /*Determine whether 100 items have been read*/ {

if(feof(fp))

printf("End of file"); /*End of file with less than 100 numbers*/

else

printf("Read error"); /* Reading error*/

fclose(fp); /*Close file*/

}

Note:

When using standard files When a function reads or writes a file, it first puts the content read and written into the buffer, that is, the writing function only operates on the output buffer, and the reading function only operates on the input buffer. For example, when writing content to a file, the written content will first be placed in the output buffer. The content of the buffer will not be saved until the output buffer is full or the file is closed using the fclose() function. Write to file. If there is no fclose()

function, the written content will not be stored in the file or the written file content will be incomplete. There is a function that refreshes the buffer, namely fflush(), and its calling format is: intfflush(FILE *stream);

This function actually writes the contents of the output buffer to the file, and The contents of the input buffer are cleared.

4. feof() and rewind() functions

The calling format of these two functions is:

intfeof(FILE *stream);

int rewind(FILE *stream);

feof()

The function detects whether the file position indicator has reached the end of the file, and if so, returns a non-0

value, otherwise 0 is returned. This function is particularly useful for binary file operations, because in binary files, the end-of-file mark EOF is also a legal binary number. It is not possible to simply check the value of the read character to determine whether the file is ended. In that case, the file may not end but be considered to be the end, so the feof() function is necessary.

The following statement is a commonly used method to determine whether a file has ended.

while(!feof(fp))

fgetc(fp);

while is a loop statement, which will be introduced below.

The rewind() function is used to move the file position indicator to the starting point of the file. It returns 0 when successful, otherwise, it returns a non-zero value.

1.2.2 Non-standard file functions

This type of function was first used in the UNIX operating system. The ANSI standard is not defined, but it is sometimes used frequently. DOS 3.0 or above supports these functions. . Their header file is io.h.

1. Opening and closing files

1. open() function

The function of open() function is to open the file, and its calling format is: < /p>

int open(char *filename, int access);

This function means to open the file named filename according to the requirements of access. The return value is the file descriptor, of which access has two parts. Content: Basic mode and modifier, the two are connected by " "(" or "). There can be multiple modifiers, but there can only be one basic mode. The access regulations are as shown in Table 3-2.

Table 3-2 access regulations

Basic mode meaning modifier meaning

O_RDONLY read-only O_APPEND file pointer points to the end

O_WRONLY Write only O_CREAT Create the file when the file does not exist, the attributes are based on the basic mode attributes

O_RDWR Read and write O_TRUNC If the file exists, reduce its length to 0, the attributes remain unchanged

O_BINARY Open a Binary file O_TEXT opens a text file

If the open() function is opened successfully, the return value is the value of the file descriptor (non-negative value), otherwise -1 is returned.

2. close() function

The function of close() is to close the file opened by the open() function. Its calling format is:

int close(int handle);

This function closes the file connected to the file descriptor handle.

The difference between Puts and gets functions

The Puts function is the same as the printf output function. They input the information in the buffer (cache) to the console, and printf inputs the information to the control The platform can control the format, such as controlling the newline symbol. The put function can only input the information intact to the console

The difference between the Gets function and the scanf function.

Both of these two functions input console information into the cache area, but the gets function can accept special symbols such as spaces and newlines, while scanf cannot. For example: for char s[23] gets(s) and scanf(“%S”,s) input characters abc de, then gets will accept abc de, while scanf only accepts abc because it cannot accept the space character after abc.