我正在尝试在 Windows 系统上实现我在 Mac 上编写的程序,但最后一个函数遇到了很多麻烦:
/* clearFiles */
// deletes the section files after the program has executed
// skips any sections listed table that don't appear in the body (b/c no file was written for these)
// also deletes the table & body files
void clearFiles(section_t *tableArray, int *skipArray, char *tableName, char *bodyName)
{
int i, status, index;
char str[SECTNAME];
char command[SECTNAME];
index = 0;
// clear section files
for(i=1; tableArray[i].count!=0;i++)
{
if(i!=skipArray[index])
{
strcpy(str, tableArray[i].shortName);
strcat(str,".txt");
status = remove(str);
if(status!=0)
printf("Warning! File %s not deleted.\n", str);
} else index++;
}
// clear table file
status = remove(tableName);
if(status!=0)
printf("Warning! File %s not deleted.\n", tableName);
// clear body file
status = remove(bodyName);
if(status!=0)
printf("Warning! File %s not deleted.\n", bodyName);
}
该程序需要一个非常大的文件,并首先将其拆分为目录文件和正文文件。然后它获取正文并将其拆分为数百个单独的部分文件,从中执行程序的实际任务。最后,我希望它删除所有这些额外的文件,因为它们只会弄乱目录。它在我的 Unix Mac 环境中完美运行,但是当我尝试在 PC 上的命令提示符中运行它时,我的 remove() 函数为每个部分文件返回 -1 并且不会删除它(但是,它确实成功删除了表和正文文件)。我还通过使用 system(del fileName) 尝试了一种更暴力的方法,但这也不起作用,因为它表示该文件正在被另一个进程使用。我无法弄清楚为什么这些文件可能会打开,因为每次 fopen() 出现时,我用 fclose() 跟进它。例外是在检查文件是否打开时,我使用
if(fopen(fileName,"r")!=NULL){}
这可能是问题吗?有没有办法检查文件是否打开而不实际打开它,或者有没有办法关闭以这种方式检查的文件?我尝试为其分配一个虚拟指针并进行编码:
dummy = fopen(fileName, "r");
if(dummy!=NULL){}
fclose(dummy);
但这也不起作用。是否可以只将文件路径传递给 fclose() 函数(例如,类似于 fclose(C:\users\USER\desktop\fileName.txt) 的东西?另外,我知道程序正在尝试删除正确的文件名,因为我的错误消息将正确的名称打印到命令提示符。
非常感谢任何输入!!!谢谢。
注意: tableArray 从 1 开始,因为程序中实现了一个搜索功能,如果找到则返回索引,如果未找到则返回 0。事后看来,如果没有找到,最好返回 -1 并将索引从零开始,但这是一个单独的问题
更新:
以下是用于创建节文件的代码:
if(fopen(word, "r")==NULL){
ofile = fopen(word, "w");
fprintf(ofile, "SECTION %s ", section);
//go until end of file or until found the next section
// bug fix: check the section after that, too (in case the next section isn't there)
while(fscanf(spec, "%s", word)!=EOF && !cease)
{
if(strcmp(word,"SECTION")!=0){
fprintf(ofile, "%s ", word);
}
else{
fscanf(spec, "%s", word);
choice = testNumber(spec,word);
for(j=i+1; tableArray[j].count!=0;j++)
if(strcmp(word,tableArray[j].shortName)==0)
cease = 1;
}
}
fclose(ofile);
}