Code前端首页关于Code前端联系我们

读取文件内容到C++程序中的方法

terry 2年前 (2023-10-01) 阅读数 325 #c++
文章标签 mybatis

一、打开文件

在C++标准库中,读取文件需要用到fstream头文件中的ifstream类。首先需要打开文件,使用ifstream类的open函数。该函数需要传递一个文件名参数,用于指定要读取的文件名。open函数执行成功后,会返回一个bool类型的值来表示文件是否打开成功。

#include<iostream>
#include<fstream>

int main()
{
    std::ifstream ifs;
    ifs.open("test.txt");
    if (!ifs)
    {
        std::cout << "Fail to open the file!" << std::endl;
        return -1;
    }
    std::cout << "File has opened successfully!" << std::endl;
    ifs.close();
    return 0;
}

二、读取文件内容

成功打开文件后,就可以使用ifstream类的read函数或者getline函数进行文件内容的读取。read函数是按字节数读取文件内容,getline函数则是按行读取文件内容。这里我们以getline函数为例,示例代码如下:

#include<iostream>
#include<fstream>
#include<string>

int main()
{
    std::ifstream ifs;
    ifs.open("test.txt");
    if (!ifs)
    {
        std::cout << "Fail to open the file!" << std::endl;
        return -1;
    }
    std::string line;
    while (getline(ifs, line))
    {
        std::cout << line << std::endl;
    }
    ifs.close();
    return 0;
}

三、关闭文件

使用完毕后,需要将已打开的文件进行关闭,以便释放资源。使用ifstream类的close函数可以实现。

#include<iostream>
#include<fstream>
#include<string>

int main()
{
    std::ifstream ifs;
    ifs.open("test.txt");
    if (!ifs)
    {
        std::cout << "Fail to open the file!" << std::endl;
        return -1;
    }
    std::string line;
    while (getline(ifs, line))
    {
        std::cout << line << std::endl;
    }
    ifs.close();
    std::cout << "File has closed successfully!" << std::endl;
    return 0;
}

四、二进制文件读取

读取二进制文件需要使用read函数。read函数需要传递两个参数:缓冲区地址和读取的字节数。

#include<iostream>
#include<fstream>

int main()
{
    std::ifstream ifs;
    ifs.open("test.bin", std::ios::binary);
    if (!ifs)
    {
        std::cout << "Fail to open the file!" << std::endl;
        return -1;
    }
    int data;
    ifs.read((char*)&data, sizeof(int));
    std::cout << data << std::endl;
    ifs.close();
    return 0;
}
以上是对在C++程序中如何读取文件内容的介绍,可以根据实际需求选择合适的方法去实现。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门