Cpp读文件、CString转String、String转CString

场景

C++读取文件

技术点

读取文件

fstream提供了三个类,用来实现c++对文件的操作。(文件的创建、读、写)。

ifstream -- 从已有的文件读入
ofstream -- 向文件写内容
fstream - 打开文件供读写

文件打开模式:

ios::in             只读
ios::out            只写
ios::app            从文件末尾开始写,防止丢失文件中原来就有的内容
ios::binary         二进制模式
ios::nocreate       打开一个文件时,如果文件不存在,不创建文件
ios::noreplace      打开一个文件时,如果文件不存在,创建该文件
ios::trunc          打开一个文件,然后清空内容
ios::ate            打开一个文件时,将位置移动到文件尾

文件指针位置在c++中的用法:

ios::beg   文件头
ios::end   文件尾
ios::cur   当前位置

例子:
移动的是字节,不是行。

file.seekg(0,ios::beg);   //让文件指针定位到文件开头 
file.seekg(0,ios::end);   //让文件指针定位到文件末尾 
file.seekg(10,ios::cur);   //让文件指针从当前位置向文件末方向移动10个字节 
file.seekg(-10,ios::cur);   //让文件指针从当前位置向文件开始方向移动10个字节 
file.seekg(10,ios::beg);   //让文件指针定位到离文件开头10个字节的位置

常用的错误判断方法:

good()   如果文件打开成功
bad()   打开文件时发生错误
eof()    到达文件尾

按行读取文件

const int bufsize = 512;
wchar_t strbuf[bufsize];
//
while (!file_.eof())
{
    file_.getline(strbuf, bufsize);
}

String转CString

c_str()函数返回一个指向正规c字符串的指针,内容和string类的本身对象是一样的,通过string类的c_str()函数能够把string对象转换成c中的字符串的样式

CString strMfc; 
std::string strStl=“test“; 
strMfc=strStl.c_str(); 

CString转String

CString到std::string:

CString cs("Hello");
std::string s((LPCTSTR)cs);

由于std::string只能从LPSTR/ 构造LPCSTR,使用VC ++ 7.x或更高版本的程序员可以使用转换类,例如作为CT2CA中介。

CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);

代码

按行读取文本文件

- 使用方式

vector<wstring> vecResult; // 文件读取的结果
wstring filename;          // 文件路径
Cpp_read_file(vecResult, filename);
        
        
- MFC

#include <fstream> 
#include <iostream> 

int CMFCClistDlg::Cpp_read_file(vector<string> &result, string szFile)
{
    //清空原始值
    result.clear();
    
    ifstream file_(szFile.c_str(), std::ios::in);

    const int bufsize = 512;
    char strbuf[bufsize];
    // 读到文件末尾
    while (!file_.eof())
    {
        file_.getline(strbuf, bufsize);

        string sentence = strbuf;
        
    
        if (sentence.empty())
        {
            continue;
        }
        result.push_back(sentence);
    }
    file_.close();
    //如果结果值为空,返回-1
    if(result.size()<1)
    {
        return -1;
    }
    return 0;
}

参考

C++读写TXT文件中的string或者int型数据以及string流的用法

https://www.cnblogs.com/1242118789lr/p/6885691.html

如何将CString和:: std :: string :: std :: wstring互相转换?

https://stackoverflow.com/questions/258050/how-to-convert-cstring-and-stdstring-stdwstring-to-each-other

转载于:https://www.cnblogs.com/17bdw/p/10279088.html