从同一个文件写入和读取

时间:2016-01-17 03:08:03

标签: c++ file

该程序接收输入,逐个字符地写入文件,计算输入的字符数,然后最后将其复制到字符数组。该程序运行正常,直到我们转到以下代码段file.getline(arr, inputLength);。它会更改.txt文件数据并仅返回原始输入的第一个字符。

有什么想法吗?

#include <iostream>
#include <fstream>

using namespace std;

int getLine(char *& arr);


int main() {
    char * arr = NULL;

    cout << "Write something: ";
    getLine(arr);
    return 0;
}


int getLine(char *& arr) {
    fstream file("temp.txt");
    char input = '\0'; //initialize
    int inputLength = 0; //initialize

    if (file.is_open()) {
        while (input != '\n') { //while the end of this line is not reached
            input = cin.get(); //get each single character
            file << input; //write it on a .txt file
            inputLength++; //count the number of characters entered
        }
        arr = new char[inputLength]; //dynamically allocate memory for this array
        file.getline(arr, inputLength); //HERE IS THE PROBLEM!!! ***
        cout << "Count : " << inputLength << endl; //test counter
        cout << "Array : " << arr << endl;         //test line copy
        file.close();
        return 1;
    }
    return 0;
}

2 个答案:

答案 0 :(得分:0)

我发现此代码至少存在两个问题。

1)默认情况下,std::fstream构造函数将打开现有文件。它不会创建一个新的。如果temp.txt不存在,is_open()将失败。此代码应将第二个参数的相应值传递给std::fstream构造函数,该构造函数指定需要创建新文件或创建现有文件。

与此相关:如果文件已经存在,则运行此代码不会截断它,因此该程序上一次运行的文件内容将有明显的意外结果。

2)此代码的目的似乎是回读之前写入其中的内容temp.txt。为了正确地做到这一点,在写入之后和阅读之前,有必要回到文件的开头。这部分似乎缺失了。

答案 1 :(得分:0)

动态分配没有必要,因为std库函数与混合参数混淆,例如cstring和指向cstring的指针。我在Visual Studio 2015编译器中测试了这段代码。它运作良好。确保包含所有需要的库:

  #include <iostream>
  #include <fstream>
  #include<cstring>
  #include<string>
  using namespace std;
  void getLine();
  int main() {

   cout << "Write something: ";

   // no need to pass a pointer to a cstring
   getLine();
   system("pause");
   return 0;
  }

     void getLine() {
      char input[100]; // this is a cstring with 
      //a safe const number of elements

      int inputLength; //to extract length of the actual input

      //this function requires cstring as a first argument
      // and constant length as a second
      cin.get(input, 100, '\n'); //get each single character

      //cast streamsize into int
     inputLength = static_cast<int>(cin.gcount());

    //testing input
    cout << "Input: \n";
    for (int i = 0; i < inputLength; i++)
     {
        cout << input[i];
     }

      cout << endl;

      char arr[100]; 

      strcpy_s(arr, input);

      cout << "Count : " << inputLength << endl; //test counter

      cout << "Array : " << endl;         //test line copy

      for (int i = 0; i < inputLength; i++)
      {
         cout << arr[i];
      }
       cout << endl;

        // write cstring to a file
       ofstream file;
       file.open("temp.txt", ios::out);
       if (file.is_open())
       {
            //write only what was entered in input
            for (int i = 0; i < inputLength; i++)
            file << arr[i];
            file.close();
        }

              else cout << "Unable to open file";
     }    
相关问题