Table of contents
1. Document prerequisite knowledge
Second, the file operation function
(2) fclose()--- close the file
2. Sequential reading and writing of files, the use of various functions
(1) fgetc and fputc -------- character input and output functions
(2) fgets and fputs--- text input and output functions
(3) fscanf and fprintf --- format input and output functions
(4) fread and fwrite---binary input and output functions
1. Document prerequisite knowledge
1. What is a document?
(1) Program files
- Including source program files (suffix .c)
- Object file (windows environment suffix is .obj)
- Executable program (windows environment suffix is .exe)
(2) Data files
2. File name
For example: c:\code\test.txt
3. File Type
- Data is stored in binary form in memory, and if it is output to external storage without conversion, it is a binary file .
- A file stored in the form of ASCII characters is a text file . (If it is required to store in the form of ASCII code on the external storage, it needs to be converted before storage)
4. File buffer
5. File pointer
Second, the file operation function
1. Open and close functions
(1) fopen()---Open the file
FILE * fopen ( const char * filename, const char * mode );
How the file is used Meaning If the file does not exist"r" (read-only) Open an existing text file for data entry Error"w" (write only) Opens a text file for outputting data Creates a new file"a" (append) Add data to the end of the text file Error"rb" (read-only) Open a binary file for input data Error"wb" (write only) Opens a binary file for data output Creates a new file
(2) fclose()--- close the file
int fclose ( FILE * stream );
/* fopen fclose example */
#include <stdio.h>
int main ()
{
FILE * pFile = fopen ("myfile.txt","w"); // 如果没有此文件,就会创建此文件。
// 同时,会销毁原文件数据
if (pFile ==NULL)
{
perror("fopen"); // 打印fopen失败原因
exit(-1);
}
.....录入数据
fclose(pFile);
pFile = null; // 防止后边解应用
return 0;
}
2. Sequential reading and writing of files, the use of various functions
Function Function Name Applies toCharacter input function fgetc all input streamsThe character output function fputc all output streamsText line input function fgets all input streamstext line output function fputs all output streamsFormat input function fscanf all input streamsFormatted output function fprintf all output streamsbinary input fread filebinary output fwrite file
(1) fgetc and fputc -------- character input and output functions
#include<stdio.h>
int main()
{
FILE* a = fopen("Test.txt", "w");
if (a ==NULL)
{
perror("fopen");
exit(-1);
}
fputc('a', a); // 输出
fputc('b', a);
fputc('c', a);
fputc('d', a);
fputc('e', a);
fclose(a);
a = fopen("Test.txt", "r"); // 重新打开文件
int ch = 0;
while ((ch = fgetc(a)) != EOF)
{
printf("%c ", ch);
}
fclose(a); // 关闭文件
a = NULL;
return 0;
}
result:
(2) fgets and fputs--- text input and output functions
Code example:
#include<stdio.h>
int main()
{
FILE* a = fopen("test.txt", "w");// 以 只写 方式打开文件
if (a ==NULL)
{
perror("fopen");
exit(-1);
}
fputs("abcdefgh", a);
fclose(a);
a = fopen("test.txt", "a"); // 重新以 增添 方式打开文件
fputs("ahuang", a);
fclose(a);
a = fopen("test.txt", "r"); // 重新以 只读 方式打开文件
char* c[20] = { 0 };
fgets(c, 20, a); // 会少打印一个字符,因为要留个位置给\0。
printf("%s", c);
fclose(a);
a = NULL;
return 0;
}
result:
(3) fscanf and fprintf --- format input and output functions
#include<stdio.h>
struct MyStruct
{
char name[20];
int age;
double size;
};
int main()
{
struct MyStruct s = { "ahuang", 20 ,60};
// 打开文件
FILE* a = fopen("Test2.txt", "w");
if (a == NULL)
{
perror("fopen");
exit(-1);
}
fprintf(a, "%s %d %lf", s.name, s.age, s.size);
fclose(a);
a = fopen("Test2.txt", "r");
struct MyStruct c = { 0 }; // 接收文件读取的数据
fscanf(a,"%s %d %lf", c.name, &(c.age), &(c.size));
fprintf(stdout, "%s %d %lf\n", c.name, c.age, c.size); // 打印到屏幕
// 上一段等价于 printf("%s %d %lf", c.name, c.age, c.size);
fclose(a);
a = NULL;
return 0;
}
result:
To add here, when a C program starts, the following three information streams are opened by default:
The standard input stream, stdin, comes from the keyboard
The standard output stream, stdout, is output to the display
The standard error stream, stderr , is output to the display
(4) fread and fwrite---binary input and output functions
The code is used as follows:
#include<stdio.h>
struct MyStruct
{
char name[20];
int age;
double size;
};
int main()
{
FILE* p1 = fopen("Text.txt", "w");
struct MyStruct k = { "阿黄", 20, 89 };
fwrite(&k, sizeof(struct MyStruct), 1, p1);
fclose(p1);
p1 = fopen("Text.txt", "r");
struct MyStruct z = { 0 };
fread(&z, sizeof(struct MyStruct), 1, p1);
printf("%s %d %lf", z.name, z.age, z.size);
return 0;
}
result:
Here is a supplement: why the binary input and output data will be garbled in Notepad:
Presentation does not match
Analysis: The first three input and output methods are saved in ASCII format, which is a text file; the last one is saved in binary format, and if the data opened with Notepad is saved in ASCII format, the binary format will be garbled.
3. File end judgment function
(1)feof
- fgetc judges whether it is EOF.
- fgets determines whether the return value is NULL.
- fread judges whether the return value is less than the actual number to be read.
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int c; // 注意:int,非char,要求处理EOF
FILE* fp = fopen("test.txt", "r");
if(!fp) {
perror("File opening failed");
return EXIT_FAILURE;
}
//fgetc 当读取失败的时候或者遇到文件结束的时候,都会返回EOF
while ((c = fgetc(fp)) != EOF) // 标准C I/O读取文件循环
{
putchar(c);
}
//判断是什么原因结束的
if (ferror(fp)) // 如果ferror返回非0,那么中间出现错误。
puts("I/O error when reading");
else if (feof(fp)) // 判断是否遇到EOF才结束,是就是正常结束。
puts("End of file reached successfully");
fclose(fp);
}
epilogue
This section is over here, thank you friends for browsing, if you have any suggestions, welcome to comment in the comment area, if you bring some gains to your friends, please leave your likes, your likes and concerns will become bloggers The driving force of the master's creation .