只有当两个文件存在时才继续程序C
问题描述:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i,x;
FILE *fl1, *fl2;
x = 0;
for(i = 0; ; i++)
{
fl1 = fopen("file1","r");
fl2 = fopen("file2","r");
if(fopen("file1","r") == NULL && fopen("file2","r") == NULL)
{
x = x + 1;
}
else break;
}
printf("\n\nDONE!\n\n");
}
我有这段代码,我希望它只在2个文件,file1和file2存在时打印完成。 但它似乎不起作用。当我只创建file1时,程序中断,如果我只创建file2,也是一样。只有当两个文件存在时才继续程序C
答
声明:
if(fopen("file1","r") == NULL && fopen("file2","r") == NULL)
如果不存在这两个文件,留下另3例(一个存在,其他的存在,或两者同时存在)被同样的方式对待只会是真实的。
如果您的目的是简单地输出DONE
如果都存在,你可以尝试:
#include <stdio.h>
int main (void) {
FILE *fl1, *fl2;
fl1 = fopen ("file1", "r");
fl2 = fopen ("file2", "r");
if (fl1 != NULL && fl2 != NULL)
printf("DONE\n");
if (fl1 != NULL) fclose (fl1);
if (fl2 != NULL) fclose (fl2);
}
这也摆脱了你更多的,应当说,... ...丰富多彩的语法结构: - )
答
您正在进行错误的测试。如果文件无法打开,则fopen
返回NULL。您的测试应该更像:
if(fopen("file1","r") != NULL && fopen("file2","r") != NULL)
编辑:也for(i = 0; ; i++)
是一个无限循环。
答
由于您在fl1和fl2中存储fopen()的返回值,只是比较它们不是NULL。
fl1 = fopen("file1","r");
fl2 = fopen("file2","r");
if(fl1 != NULL && fl2 != NULL)
{
printf("\nDONE!");
}
答
你应该写
FILE *fin1 = fopen("file1", "r");
FILE *fin2 = fopen("file2", "r");
if (fin1 != NULL && fin2 != NULL)
{
// Do your work
fclose(fin1);
fclose(fin2);
}
else
{
// some file didn't open. Close the other possible open one and return error
if (fin1)
fclose(fin1);
if (fin2)
fclose(fin2);
// give error;
}
注意fclose
部分。关闭您打开的文件非常重要。例如,如果您稍后想要再次打开它。一般来说,无论您从操作系统获取什么资源(例如内存,文件,套接字等),都有责任返回它。
答
如果您只是想检查文件是否存在,而不是打开它们,请使用access()
,例如。
#include <unistd.h>
if (!access("file1", F_OK) && !access("file2", F_OK))
{
/* Files exist, do something */
}
你的意思是1. _only_这两个文件完全存在于文件夹中或者2.这两个文件都存在于文件夹_at least_? – holex