温馨提示×

C/C++文件API简单操作

c++
小云
83
2024-01-13 03:56:19
栏目: 编程语言

C/C++文件API是一组可以用于操作文件的函数,包括创建、打开、读写、关闭等操作。下面是一些常见的C/C++文件API的简单操作示例:

  1. 创建文件:
#include <stdio.h>

int main() {
    FILE *file;
    file = fopen("example.txt", "w");  // 打开文件,如果不存在则新建
    if (file == NULL) {
        printf("无法创建文件\n");
        return 1;
    }
    fclose(file);  // 关闭文件
    return 0;
}
  1. 写入文件:
#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;
}
  1. 读取文件:
#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;
}
  1. 追加内容到文件:
#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;
}

这些示例只是C语言中部分文件API的基本用法,C++中也有类似的文件操作函数。在实际开发中,还有更多的文件操作函数和错误处理机制需要考虑。

0