C/C++文件API是一組可以用于操作文件的函數(shù),包括創(chuàng)建、打開、讀寫、關(guān)閉等操作。下面是一些常見的C/C++文件API的簡單操作示例:
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "w"); // 打開文件,如果不存在則新建
if (file == NULL) {
printf("無法創(chuàng)建文件\n");
return 1;
}
fclose(file); // 關(guān)閉文件
return 0;
}
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "w");
if (file == NULL) {
printf("無法打開文件\n");
return 1;
}
fprintf(file, "Hello, World!\n"); // 寫入內(nèi)容
fclose(file);
return 0;
}
#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); // 讀取一行內(nèi)容
printf("讀取內(nèi)容:%s", buffer);
fclose(file);
return 0;
}
#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"); // 追加內(nèi)容
fclose(file);
return 0;
}
這些示例只是C語言中部分文件API的基本用法,C++中也有類似的文件操作函數(shù)。在實際開發(fā)中,還有更多的文件操作函數(shù)和錯誤處理機(jī)制需要考慮。