c++ - 删除 fopen 成功创建的文件时权限被拒绝

标签 c++ file

这是一个函数,它从用户那里获取文件夹名称,创建一个文本文件,稍后应该将其删除。

void function(string LogFolder)
{
     fopen((LogFolder+"/test.txt").c_str(),"w");
     cout<<"The errorno of fopen "<<errno<<endl;
     remove((LogFolder+"/test.txt").c_str());
     cout<<"The errorno of remove "<<errno<<endl;
}

输出:
fopen 0的errorno【说明文件创建成功】
remove 13的errorno[表示Permission denied]

如您所见,该文件夹被成功删除。
A link to understand error codes

最佳答案

您需要先关闭文件:

void function(string LogFolder)
{
     // Acquire file handle
     FILE* fp = fopen((LogFolder+"/test.txt").c_str(),"w");

     if(fp == NULL) // check if file creation failed
     {
          cout<<"The errorno of fopen "<<errno<<endl;
          return;
     }

     // close opened file
     if(fclose(fp) != 0)
     {
         cout<<"The errorno of fclose "<<errno<<endl;
     }


     if(remove((LogFolder+"/test.txt").c_str()) != 0)
     {
          cout<<"The errorno of remove "<<errno<<endl;
     }
}

关于c++ - 删除 fopen 成功创建的文件时权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20237676/

相关文章:

c++ - 是否需要删除未实例化为变量的指针?

C++(以某种方式)将结构限制为父 union 大小

Java ArrayList IndexOutOfBoundsException 索引 : 1, 大小:1

c - 跨线程拆分文本文件

c++ - 哪些库用于 3d 表面网格

c++ - 在类中初始化固定大小的常量数组

android - setReadOnly 不工作

java - 在Java中,如何在外部文件之前加载jar中的资源?

c++ - 带对象方法的线程

python - 如何将 _io.TextIOWrapper 转换为字符串?