使用 fclose() 关闭文件,但文件仍在使用中

发布于 2024-10-12 01:23:47 字数 2958 浏览 3 评论 0原文

我在使用我的程序删除/覆盖文件时遇到问题,该程序也正在被我的程序使用(读取)。问题似乎在于,由于我的程序正在从文件(output.txt)读取数据,因此它会将文件置于“使用中”状态,这使得无法删除或覆盖该文件。

我不明白为什么该文件保持“使用中”状态,因为我在使用 fclose(); 使用后关闭了该文件;

这是我的代码:

bool bBool = true

while(bBool){
  //Run myprogram.exe tot generate (a new) output.txt

  //Create file pointer and open file
  FILE* pInputFile = NULL;
  pInputFile = fopen("output.txt", "r");
  //
  //then I do some reading using fscanf()
  //
  //And when I'm done reading I close the file using fclose()
  fclose(pInputFile);

  //The next step is deleting the output.txt
  if( remove( "output.txt" ) == -1 ){
    //ERROR
  }else{
    //Succesfull
  }
}

我使用 fclose() 关闭文件,但该文件仍由我的程序使用,直到我的程序完全关闭。

释放文件以便删除/覆盖的解决方案是什么?

实际上,我的代码不是一个没有结束的循环; )

提前致谢!

Marco

更新

就像询问我的代码的一部分一样,它也会生成“正在使用”的文件。这不是循环,并且该函数是从 main() 调用的;

这是一段代码:

int iShapeNr = 0;

void firstRun()
{
    //Run program that generates output.txt
    runProgram();

    //Open Shape data file
    FILE* pInputFile = NULL;
    int iNumber = 0;
    pInputFile = fopen("output.txt", "r");

    //Put all orientations of al detected shapes in an array
    int iShapeNr = 0;
    int iRotationBuffer[1024];//1024 is maximum detectable shapes, can be changed in RoboRealm
    int iXMinBuffer[1024];
    int iXMaxBuffer[1024];
    int iYMinBuffer[1024];
    int iYMaxBuffer[1024];

    while(feof(pInputFile) == 0){       
        for(int i=0;i<9;i++){
            fscanf(pInputFile, "%d", &iNumber);
            fscanf(pInputFile, ",");
            if(i == 1) {
                iRotationBuffer[iShapeNr] = iNumber;
            }
            if(i == 3){//xmin
                iXMinBuffer[iShapeNr] = iNumber;
            }
            if(i == 4){//xmax
                iXMaxBuffer[iShapeNr] = iNumber;
            }
            if(i == 5){//ymin
                iYMinBuffer[iShapeNr] = iNumber;
            }
            if(i == 6){//ymax
                iYMaxBuffer[iShapeNr] = iNumber;
            }
        }
        iShapeNr++;
    }
    fflush(pInputFile);
    fclose(pInputFile);

}

while 循环解析文件。 output.txt 包含 9 个变量的集合,集合的数量未知,但始终为 9 个集合。output.txt

可以包含例如:0,1,2,3,4,5,6,7,8,8 ,7,6,5,4,1,2,3,0

更新 2

代码:

    void runProgram(){
    //Check if output.txt exists, if so delete it
    if(fileExists("output.txt") == 1){
        //Delete output.txt
        if( remove( "output2.txt" ) == -1 ){
            //errormessage
        }else{
            //succesfull
        }
    }   
    //start program
    ShellExecute( NULL, TEXT("open"), TEXT("program.exe"), NULL, NULL, SW_SHOWMAXIMIZED);

    while(fileExists("output.txt") == 0);

    //Close program
    int iCheck = system("taskkill /IM program.exe");
    if(iCheck != 0){
        //error could not shut down
    }
}

抱歉再次使用 pre,但我不明白此网站的格式:(

I've got a problem with deleting/overwriting a file using my program which is also being used(read) by my program. The problem seems to be that because of the fact my program is reading data from the file (output.txt) it puts the file in a 'in use' state which makes it impossible to delete or overwrite the file.

I don't understand why the file stays 'in use' because I close the file after use with fclose();

this is my code:

bool bBool = true

while(bBool){
  //Run myprogram.exe tot generate (a new) output.txt

  //Create file pointer and open file
  FILE* pInputFile = NULL;
  pInputFile = fopen("output.txt", "r");
  //
  //then I do some reading using fscanf()
  //
  //And when I'm done reading I close the file using fclose()
  fclose(pInputFile);

  //The next step is deleting the output.txt
  if( remove( "output.txt" ) == -1 ){
    //ERROR
  }else{
    //Succesfull
  }
}

I use fclose() to close the file but the file remains in use by my program until my program is totally shut down.

What is the solution to free the file so it can be deleted/overwrited?

In reality my code isn't a loop without an end ; )

Thanks in advance!

Marco

Update

Like ask a part of my code which also generates the file 'in use'. This is not a loop and this function is being called from the main();

Here is a piece of code:

int iShapeNr = 0;

void firstRun()
{
    //Run program that generates output.txt
    runProgram();

    //Open Shape data file
    FILE* pInputFile = NULL;
    int iNumber = 0;
    pInputFile = fopen("output.txt", "r");

    //Put all orientations of al detected shapes in an array
    int iShapeNr = 0;
    int iRotationBuffer[1024];//1024 is maximum detectable shapes, can be changed in RoboRealm
    int iXMinBuffer[1024];
    int iXMaxBuffer[1024];
    int iYMinBuffer[1024];
    int iYMaxBuffer[1024];

    while(feof(pInputFile) == 0){       
        for(int i=0;i<9;i++){
            fscanf(pInputFile, "%d", &iNumber);
            fscanf(pInputFile, ",");
            if(i == 1) {
                iRotationBuffer[iShapeNr] = iNumber;
            }
            if(i == 3){//xmin
                iXMinBuffer[iShapeNr] = iNumber;
            }
            if(i == 4){//xmax
                iXMaxBuffer[iShapeNr] = iNumber;
            }
            if(i == 5){//ymin
                iYMinBuffer[iShapeNr] = iNumber;
            }
            if(i == 6){//ymax
                iYMaxBuffer[iShapeNr] = iNumber;
            }
        }
        iShapeNr++;
    }
    fflush(pInputFile);
    fclose(pInputFile);

}

The while loop parses the file. The output.txt contains sets of 9 variables, the number of sets is unknown but always in sets of 9.

output.txt could contain for example: 0,1,2,3,4,5,6,7,8,8,7,6,5,4,1,2,3,0

update 2

code:

    void runProgram(){
    //Check if output.txt exists, if so delete it
    if(fileExists("output.txt") == 1){
        //Delete output.txt
        if( remove( "output2.txt" ) == -1 ){
            //errormessage
        }else{
            //succesfull
        }
    }   
    //start program
    ShellExecute( NULL, TEXT("open"), TEXT("program.exe"), NULL, NULL, SW_SHOWMAXIMIZED);

    while(fileExists("output.txt") == 0);

    //Close program
    int iCheck = system("taskkill /IM program.exe");
    if(iCheck != 0){
        //error could not shut down
    }
}

sorry for using pre again but I don't get the formatting of this site :(

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

旧竹 2024-10-19 01:23:47

是否是由于已达到最大磁盘空间并且文件中仍有数据
流缓冲区; fclose 文件流会刷新它(写入缓冲区中的所有数据),由于达到最大磁盘空间,写入操作将失败。

我建议您在 fopen() 之后直接调用 fclose() 来缩小问题范围。
如果成功,则 fclose() 和 fopen() 之间的代码有问题。

Will it be due to maximum disk space has been reached and there's still data in the file
streams buffer; fclose'ing a file stream flushes it (writes all the data in the buffer), the write operation will fail since maximum disk space is reached.

I suggest you to scope down the problem, by calling fclose() directly after fopen().
If it success, then something is wrong in the code between fclose() and fopen().

殊姿 2024-10-19 01:23:47

您的代码中可能还有其他地方没有调用fclose,从而泄漏了文件。即使在这段代码中,如果 fopen 和 fclose (或 return 语句、或 continue 语句等)之间发生错误,您也会泄漏文件。请切换到 RAII 习惯用法。

编辑:将其包含到您的代码中:

struct PoorMansFile {
    FILE *_file;
    PoorMansFile(const char* str1, const char* str2) : _file(fopen(str1,str2)) {}
    ~PoorMansFile() { if(_file) fclose(_file); }
    operator FILE*() const { return _file; }
};
int fclose(PoorMansFile& file)
{ 
    if(!file) 
        return 0;

    int t = fclose(file._file);
    file._file = 0; 
    return t; 
}

并将每个替换

FILE* file = NULL;
file = fopen(str1, str2);

为:

PoorMansFile file(str1, str2);

告诉我们是否有帮助;

There is probably other places in your code where you don't call fclose, leaking the file. Even in this code, if an error occurs between fopen and fclose (or a return statement, or a continue statement, etc...) you'll leak the file. Please, switch to RAII idiom.

Edit: include this into your code:

struct PoorMansFile {
    FILE *_file;
    PoorMansFile(const char* str1, const char* str2) : _file(fopen(str1,str2)) {}
    ~PoorMansFile() { if(_file) fclose(_file); }
    operator FILE*() const { return _file; }
};
int fclose(PoorMansFile& file)
{ 
    if(!file) 
        return 0;

    int t = fclose(file._file);
    file._file = 0; 
    return t; 
}

and replace each

FILE* file = NULL;
file = fopen(str1, str2);

with:

PoorMansFile file(str1, str2);

Tell us if it helps;

萌︼了一个春 2024-10-19 01:23:47

该文件可能仍被 CRT 或操作系统使用 - 例如,操作系统可能会缓冲对磁盘的写入。 fflush() 只会刷新 CRT 缓冲区,而不刷新操作系统缓冲区。

The file could still be in use by the CRT or OS - for example, the OS may buffer writes to the disk. fflush() will only flush CRT buffers, not OS buffers.

全部不再 2024-10-19 01:23:47

只是在黑暗中拍摄......

runProgram() 里面是什么?该函数是否会等到程序完成后再返回?我想知道正在写入数据的程序实际上是否仍在运行......从这里很难判断,但我想我会把它扔掉!

Just a shot in the dark here...

What is inside runProgram()? Does that function wait until the program has finished before returning? I wonder if the program that is writing the data is, in fact, still running... it's difficult to tell from here, but thought I'd throw it out there!

謸气贵蔟 2024-10-19 01:23:47

阅读所有答案和评论后,我想不出OP问题的任何原因。

这是多线程还是可重入例程?

如果对同一个文件执行两次 fopen 和两次 fclose 会发生什么?这可能是问题的原因吗?

在这个想法中,我建议再进行两项检查。

  • printf fclose 后所有 fopen/fclose 调用
  • 将文件变量重置为 NULL

f = fopen("", ""); printf("fopen => %p", f);
f关闭(f); printf("fclose => %p", f); f = 0;

如果您不方便使用 printf 调试,可以使用 OutputDebugString。

extern void __stdcall OutputDebugStringA(const char*)(仅限 MS VC)

After reading all answers and comments I could not think of any reason of OP's problem.

Is this multi threaded or reentrant routine?

What will happen if fopen twice and fclose twice on the same file? Is this could be the cause of the problem?

In this thought I suggest two more checks.

  • printf all fopen/fclose call
  • after fclose reset file variable to NULL

f = fopen("", ""); printf("fopen => %p", f);
fclose(f); printf("fclose => %p", f); f = 0;

If you are inconvenient with printf debugging you can use OutputDebugString.

extern void __stdcall OutputDebugStringA(const char*) (MS VC only)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文