c++ - 如何在 C++ 中打开文件?

标签 c++ file io

我想以 C++ 方式打开一个文件进行读取。我需要能够做到:

  • 文本文件,会涉及到某种读行功能。

  • 二进制文件,可以将原始数据读入 char* 缓冲区。

最佳答案

您需要使用 ifstream如果您只是想阅读(使用 ofstream 来编写,或者使用 fstream 来编写两者)。

要以文本模式打开文件,请执行以下操作:

ifstream in("filename.ext", ios_base::in); // the in flag is optional

要以二进制模式打开文件,只需添加“二进制”标志。

ifstream in2("filename2.ext", ios_base::in | ios_base::binary ); 

使用 ifstream.read()读取字符 block 的函数(以二进制或文本模式)。使用 getline()读取整行的函数(它是全局的)。

关于c++ - 如何在 C++ 中打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7880/

相关文章:

c - 无法使文件 I/0 在周期计数器功能 -c 中工作

c++ - 使用 marmalade SDK 的内存使用问题

python - 应用程序需要一个文件系统元数据层

file - 如何将结构作为二进制数据写入golang中的文件?

python - 将多个 numpy 数组写入文件

JavaIO : Using scanner and printWriter to copy the contents of a text file and put them in another text file

c++ - const在不同地方的c++中是什么意思

c++ - 指针数组困惑

c++ - 什么是 : MultiByteToWideChar & WideCharToMultiByte? 的 Linux 等价物

file - yii 使用函数导入文件