我在使用我的程序删除/覆盖文件时遇到问题,该文件也被我的程序使用(读取)。问题似乎是因为我的程序正在从文件 (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() 关闭该文件,但该文件仍由我的程序使用,直到我的程序完全关闭。
释放文件以便删除/覆盖它的解决方案是什么?
实际上,我的代码并不是没有尽头的循环; )
提前致谢!
马可
更新
就像询问我的代码的一部分一样,它也会生成“正在使用”的文件。这不是一个循环,这个函数是从 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 但我不明白这个网站的格式 :(
最佳答案
会不会是因为已经达到最大磁盘空间,文件中还有数据 流缓冲器; fclose 文件流将其刷新(将所有数据写入缓冲区),写入操作将失败,因为已达到最大磁盘空间。
我建议您通过在 fopen() 之后直接调用 fclose() 来缩小问题的范围。 如果成功,则说明 fclose() 和 fopen() 之间的代码有问题。
关于c++ - 使用 fclose() 关闭文件但文件仍在使用中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4666800/