【发布时间】:2011-01-12 08:51:12
【问题描述】:
我在使用我的程序删除/覆盖文件时遇到问题,我的程序也在使用(读取)该文件。问题似乎是因为我的程序正在从文件(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 但我没有得到这个网站的格式:(
【问题讨论】:
-
您是否使用 strerror/perror 来诊断问题所在?你在什么操作系统上?
-
您是否在 fclose() 之前尝试过 fflush() 文件?
-
@Bart,这不是必需的,
flcose()会解决这个问题。 @Marco,正如@Henno Brandsma 所说,检查errno并查看它的内容,这可能会给你一些线索。顺便说一句,这是标记为 C++,你为什么不使用 IO 流?? -
你总是需要检查
fclose()返回值。 -
他在读文件的时候,有必要打电话给
fflush吗?