我在使用我的程序删除/覆盖文件时遇到问题,该程序也被我的程序使用(读取)。问题似乎是因为我的程序正在从文件(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 但我没有得到这个网站的格式:(