2013-11-27 91 views
1

这是一个从用户处获取文件夹名称,创建文本文件并在稍后将其删除的功能。删除fopen成功创建的文件时权限被拒绝

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; 
} 

OUTPUT:[意思是文件已成功创建]
的的fopen 0 errorno
除去13的errorno [就是说拒绝权限]

正如你可以看到该文件夹已成功删除而不是
A link to understand error codes

+3

在尝试删除文件夹之前,您应该使用'fclose()'。 –

+3

除非您真的知道上一个功能失败,否则不要检查errno。如果一个函数没有失败,'errno'的值是未指定的。 –

+0

会记住这一点。 – iajnr

回答

3

您需要首先关闭文件:

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; 
    } 
} 
+0

完美工作。 – iajnr

1

您可能需要设置文件夹的执行权限以及写入权限。

1

这是因为该文件仍处于打开状态。你应该在fclose()它删除文件夹之前。 喜欢的东西

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

工作完美。谢谢。 – iajnr

2

对于初学者来说,你是不是创建和删除文件夹,而是一个文件名为test.txt文件夹内。

您的问题是,您需要先关闭文件,然后才能将其删除。请尝试以下操作

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

编辑这个问题,修复工作完美。 – iajnr

相关问题