如何从文本文件创建char *数组而无需打开和关闭两次

时间:2019-06-23 16:44:48

标签: c++

在下面的代码中,我打开一个文本文件,计算行数,然后创建一个文件长度的char*数组。然后,我关闭文件并重新打开它以遍历文件,以创建一个包含文件内容的数组。

有没有一种方法可以只打开和关闭文件的一个数组?

#include <iostream>
#include <fstream>

using namespace std;

void myfunc(char *arr);


int main()
{
  // https://www.includehelp.com/cpp-programs/write-read-text-in-file.aspx
  fstream file;  // object of fstream class

  // open the file in read mode (in)
  file.open("name.txt", ios::in);

  // read until end of file is not found
  char ch;  // read single character
  cout << "file content: ";

  int numplaces = 0;
  while(!file.eof())
  {
    file >> ch;  // read single character from File
    cout << ch;
    numplaces += 1;
  }
  cout << numplaces << endl;

  // Create a list of strings:
  // https://stackoverflow.com/questions/11938829/declare-fixed-size-character-array-on-stack-c
  char* str = new char[numplaces];

  myfunc(str);

  while (!file.eof())
  {
    file >> ch;
    cout << ch;
  }
  cout << sizeof(str) << endl;

  file.close();

  // open the file in read mode (in)
  file.open("name.txt", ios::in);
  int linecount = 0;
  while(!file.eof())
  {
    file >> ch;  // read single character from File
    str[linecount] = ch;
    linecount += 1;
  }
  file.close();
  myfunc(str);
  return 0;
}

void myfunc(char *str)
{
  for( unsigned int a = 0; a < sizeof(str)/sizeof(str[0]); a = a + 1 )
  {
    cout << str[a] << endl;
  }
}

0 个答案:

没有答案