【问题标题】:WriteFile not doing anythingWriteFile 没有做任何事情
【发布时间】:2012-08-11 15:00:53
【问题描述】:

嘿,我的 write 和 readFile 方法有问题。这些方法不做任何事情。该方法应该将动态数组的元素写入名为 C++ 的文件中。 然后对于读取的文件,该方法应该是读取ArrayList的元素。

这是我的代码: 方法

//---------------------------------------------------------------------------------------
//  Name:         Array::WriteFile
//  Description:  Writes an array to disk
//  Arguments:    The Filename
//  Return Value: true on success, false on failure
//---------------------------------------------------------------------------------------
   void writeFile(string file)//saves the array elements into a text file
    {
        //sort();
        ofstream outfile(file);//allows you to write to the document passed in
        for(int i = 0; i < m_size; i++)//loops through the array
        {
            outfile << m_array[i] << endl;//saves each element into a single line in the text document
        }
        outfile.close();
    }


//---------------------------------------------------------------------------------------
//  Name:         ReadFile.
//  Description:  Reads an array from disk.
//  Arguments:    The Filename.
//  Return Value: True on success, false on failure.
//---------------------------------------------------------------------------------------
   void readFile(string file)
    {
        ifstream inFile(file);//reads the file
        string line;//creates a string to take in information from the text deocument
        int numLines=0;//number of lines read in text document so far

        while(getline(inFile, line))//loops through the text document counting how many lines are in it.
        {
            numLines++;//increments every time a line is read
        }
        Datatype object;//creates a variable of type DataType to hold whatever is in the text document be it int, float, string etc...
        inFile.clear() ;//these two lines reset the inFile and go back to the start allowing to read through it again
        inFile.seekg(0, ios::beg) ;
        for(int i = 0; i < numLines; i++)//loops for whatever the number of lines there is in the document.
        {
            inFile >> object;//pushes the line into the document into object
            push(object);//calls the push function that will push object into the array in the right order
        }
        inFile.close();

    }

如果还需要什么,尽管问,我会发布。

【问题讨论】:

  • 如果您只想阅读它们,您应该通过const&amp; 传递字符串,就像在您的示例中一样。看stackoverflow.com/questions/10836221/…
  • 这些是类的成员函数吗?
  • 创建输出流后,我建议检查文件是否打开:if (outfile.is_open()) ....
  • 您没有检查任何流使用的错误。如果你这样做了,那么你就会知道哪里出了问题,这将有助于找出原因。
  • @Pendo826:所以您的文件无法打开,这就是为什么没有写入但可能还有更多的原因之一。你检查过file的内容吗?更重要的是,您是否使用调试器单步执行了代码?

标签: c++ file-io arraylist


【解决方案1】:

问题在于目录权限。因为它只被读取而不被写入,所以文档从未被写入。

【讨论】:

    猜你喜欢
    • 2012-09-07
    • 2016-10-02
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多