以下是一个将字符写入 C 盘 test.txt 文件的 C++ 代码示例:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    char ch = 'A'; // 要写入的字符
    ofstream outfile; // 创建输出文件流对象
    outfile.open("C:\\test.txt"); // 打开文件,这里写入 C 盘根目录下的 test.txt 文件
    if (outfile.is_open()) { // 判断文件是否打开成功
        outfile << ch; // 将字符写入文件
        outfile.close(); // 关闭文件
        cout << "写入成功" << endl;
    }
    else {
        cout << "文件打开失败" << endl;
    }
    return 0;
}

注意:在 Windows 系统中,C 盘根目录下的文件需要使用双反斜杠(\)来表示路径。此外,如果文件不存在,程序会自动创建一个新文件。

C++ 写入文本文件:将字符写入 C 盘

原文地址: https://www.cveoy.top/t/topic/nF1e 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录