Simple operation of file API in C/C++
The C/C++ file API is a set of functions used for manipulating files, such as creating, opening, reading, writing, and closing. Here are some common examples of simple file operations using the C/C++ file API:
- Create a file.
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "w"); // 打开文件,如果不存在则新建
if (file == NULL) {
printf("无法创建文件\n");
return 1;
}
fclose(file); // 关闭文件
return 0;
}
- Write to file.
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "w");
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
fprintf(file, "Hello, World!\n"); // 写入内容
fclose(file);
return 0;
}
- Read the file:
#include <stdio.h>
int main() {
FILE *file;
char buffer[255];
file = fopen("example.txt", "r");
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
fgets(buffer, sizeof(buffer), file); // 读取一行内容
printf("读取内容:%s", buffer);
fclose(file);
return 0;
}
- Add additional content to the file.
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "a");
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
fprintf(file, "This is appended content.\n"); // 追加内容
fclose(file);
return 0;
}
These examples only cover the basic usage of some file APIs in the C language, and there are similar file operation functions in C++. In actual development, there are also more file operation functions and error handling mechanisms to consider.