如何使用c++将一个不同长度的完整.txt文件读取到一个数组中

How do i read an entire .txt file of varying length into an array using c++?

本文关键字:一个 文件 txt 读取 数组 c++ 何使用      更新时间:2023-10-16

我正在制作一个移位密码,它从文件中读取文本并对其进行解码。解密效果很好,但如果不将文件硬编码为char数组的大小,我就无法找到文件的长度。它也只读一行,任何带有换行符的内容都会损坏。

如果有任何帮助,我们将不胜感激,我省略了处理数组的主要代码块,因为它在读入后看起来有点长,而且不相关。

string fileName;
cout << "Please enter the locations of your encrypted text (e.g ""encryptedText.txt""): ";
getline( cin, fileName );
char encryptedMessage[446]; //How do i read in the file length and declare the array size as a variable instead of [446]?
char decryptedMessage[446];
ifstream in(fileName);
if(in.get(encryptedMessage, 446))
{
  [my decrypting code]
}
else
{
cout << "Couldn't successfully read file.n";
}
system("pause");

好吧,将整个文件读取到动态大小的字符数组(不要使用静态大小的数组)中的简单一行代码是:

#include <vector>
#include <iterator>
std::vector<char> encryptedMessage(std::istreambuf_iterator<char>(in),
                                   std::istreambuf_iterator<char>());

不要自己搞动态分配,只需让std::vector完成它的工作即可。由于其优化的增长行为,您实际上不需要检查文件大小。必要时优化速度,或者至少在文件超过几百个字符之前进行优化。当然,istreambuf_iterator(而不是istream_iterator)并没有处理任何特殊的空白,它只是从文件中一个接一个地提取每个字符。

您可以对std::string而不是std::vector<char>执行同样的操作,但我不确定它的增长行为(也许它总是用一个元素重新分配数组)。但话说回来,当文件包含400个字符时,谁会关心速度呢?

您可以使用seekg来获取整个文件的大小:

#include <iostream>
#include <fstream>
using namespace std;
int main () {
  long begin_byte, end_byte;
  ifstream in("example.txt");
  begin_byte = in.tellg();
  in.seekg (0, ios::end);
  end_byte = in.tellg();
  int total_bytes = end_byte - begin_byte;
  in.seekg(0, ios::begin);
  char *message = new char[total_bytes + 1];
  int index = 0;
  while (in) {
    message[index++] = in.get();
  }
  in.close();
  cout << "message is: " << message << endl;
  delete [] message;
  return 0;
}

您可以在这里阅读更多关于seekg、tellg和c++中的文件的内容。

然而,与使用char*相比,更好的解决方案是使用std:string,并在in尚未结束时对其调用push_back:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
  ifstream in("example.txt");
  string message;
  while (in) {
    message.push_back(in.get());
  }
  in.close();
  cout << "message is: " << message << endl;
  return 0;
}

在C++中不能有可变长度数组(VLA)
编译器确实提供VLA作为扩展,但使用它们会使代码不可移植。

最简单也是最好的解决方案是使用std::string而不是字符数组。

您可能会得到关于使用动态分配数组的所有建议的答案,但使用std::string是最佳选择,因此请忽略这些建议。

编辑:
既然有人否决了这个。我很想知道这样做的原因(前提是它们是技术性的)。

您需要动态分配内存,而管理内存的最佳方法是使用std::vector

std::vector<char> encryptedMessage;
encryptedMessage.resize(size_of_file);
in.get(&encryptedMessage[0], encryptedMessage.size());
相关文章: