【问题标题】:c++ i/o locks an empty filec++ i/o 锁定一个空文件
【发布时间】:2015-12-08 11:02:29
【问题描述】:

我创建了一个函数来返回文件的大小

int thFileClass::getFileSize (){
streampos begin,end;
ifstream myfile (m_szFile,std::ios::binary);
if (myfile.peek() != std::ifstream::traits_type::eof()){
    if (myfile.is_open()){
        begin = myfile.tellg();
        myfile.seekg (0, myfile.end);
        end = myfile.tellg();
        myfile.close();
        cout << "size is: " << (end-begin) << " bytes.\n";
        return end-begin;
    } 
} else {
    myfile.close();
}
return 0;
}

但是如果文件是空的,它会锁定它。所以下次我打开文件进行读/写时它不会打开 MyFile.is_open()==false;

任何想法为什么会这样或者我可以如何阻止文件锁定?

附:我的文件.close();总是在上述函数中调用。

更新

即使我的代码很简单,例如打开和关闭文件,它也会被锁定。

ifstream myfile (m_szFile,std::ios::binary);
myfile.close();

【问题讨论】:

  • 如果您不赞成,请发表评论

标签: c++ io ifstream


【解决方案1】:

试试这个

int getFileSize() {
        streampos begin, end;
        ifstream myfile("1.txt");
        if (myfile.peek() != std::ifstream::traits_type::eof()) {
            if (myfile.is_open()) {
                begin = myfile.tellg();
                myfile.seekg(0, myfile.end);
                end = myfile.tellg();
                myfile.close();
                cout << "size is: " << (end - begin) << " bytes.\n";
            }
        }
        myfile.close();
        return end - begin;
    }

【讨论】:

  • 即使我做 ifstream myfile (m_szFile,std::ios::binary);我的文件.close();文件被锁定
  • 所有作品。当你的文件被锁定?在您的代码中,如果 myfile.peek() != std::ifstream::traits_type::eof() 为真,那么您没有关闭文件
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
相关资源
最近更新 更多