如何在 c++ 中将整个文本文件复制到 char 数组中

How to copy a whole text file into a char array in c++

本文关键字:复制 文件 数组 char 文本 c++      更新时间:2023-10-16
int main()
{
char ch;
char text[500];
char s[500];
ifstream fin("bitch.txt",ios::in);
while(!fin.eof())
{
fin.getline(s,500);
}
fin.close();
for (int i=0; i<500; i++)
{
   cout << s[i];
}
return 0;
}

如何在 c++ 中将整个文本文件内容复制到 char 数组中考虑到文本文件包含 100 个字符长的段落我也需要阅读空格.

就这样做

#include <string>
#include <fstream>
#include <streambuf>
std::ifstream file("file.txt");
std::string str((std::istreambuf_iterator<char>(file)),
                 std::istreambuf_iterator<char>());

然后

str.c_str();

是您查找的数组。

如果要

将文件的全部内容复制到char数组中,则无需逐行执行此操作。您可以复制文件的全部内容

您可以使用以下命令将整个文件读入字符串

std::ifstream in("FileReadExample.cpp");
std::string contents((std::istreambuf_iterator<char>(in)), 
std::istreambuf_iterator<char>());

然后你可以使用 contents.c_str() 来获取字符数组

看看下面的链接。 他给出了正确的答案如何在 c++ 中将.txt文件复制到字符数组