c++ 读写文件

ifstream inFile1;
        inFile1.open("a.txt", ios_base::in);
        if (!inFile1.is_open())
        {
                cout<<"打开导入文件文件失败,请检查是否存在导入文件"<<endl;
                return false;
        }

        char szBuffer1[120] = "0";
        string str1;
        while (getline(inFile1,str1))
        {
                cout<<str1<<endl;
        }
        //cout<<inFile1.rdbuf()<<endl;
        inFile1.close();

写文件例子:

        string sql = "test";
        ofstream outFile;
        outFile.open(strExportFileName.c_str(), ios_base::app);
        if (!outFile.good())
        {
                cout<<"打开文件失败"<<endl;
                return false;
        }
        outFile<<sql;
        outFile.close();

C++ 中,常用的读写文件的 API 主要有以下几种: 1. fstream 类:C++ 标准库提供的文件读写类,可以用于读写文本文件和二进制文件。它继承自 istream 和 ostream 类,因此可以使用流操作符 << 和 >> 来进行读写操作。示例代码: ```c++ #include <fstream> #include <iostream> int main() { // 写入文件 std::ofstream ofs("example.txt"); ofs << "Hello, world!" << std::endl; ofs.close(); // 读取文件 std::ifstream ifs("example.txt"); std::string line; std::getline(ifs, line); std::cout << line << std::endl; ifs.close(); return 0; } ``` 2. fopen 和 fclose 函数:C 语言标准库提供的文件读写函数,可以用于读写文本文件和二进制文件。需要注意的是,fopen 函数返回的是一个指向 FILE 结构体的指针,需要使用 fclose 函数关闭文件。示例代码: ```c++ #include <stdio.h> int main() { // 写入文件 FILE* fp = fopen("example.txt", "w"); fprintf(fp, "Hello, world!\n"); fclose(fp); // 读取文件 fp = fopen("example.txt", "r"); char buf[1024]; fgets(buf, 1024, fp); printf("%s", buf); fclose(fp); return 0; } ``` 3. read 和 write 函数:C 语言标准库提供的文件读写函数,用于读写二进制文件。read 函数可以读取指定字节数的数据到指定的缓冲区中,write 函数可以将指定字节数的数据从指定的缓冲区中写入到文件中。示例代码: ```c++ #include <fcntl.h> #include <unistd.h> int main() { // 写入文件 int fd = open("example.bin", O_WRONLY | O_CREAT, 0644); char buf[] = {0x01, 0x02, 0x03, 0x04}; write(fd, buf, sizeof(buf)); close(fd); // 读取文件 fd = open("example.bin", O_RDONLY); char buf2[4]; read(fd, buf2, sizeof(buf2)); close(fd); return 0; } ``` 需要注意的是,使用 read 和 write 函数时需要使用 open 函数打开文件,并指定打开方式和权限等参数。而使用 fstream 类和 fopen 函数时,可以通过构造函数或者 fopen 函数的第二个参数来指定打开方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值