检测不存在的文件

所以这是我用过的第一个程序之一,我自己创建了一些自我创建的错误检查,但是出于某种原因,当我编译它并运行它时:

./file test1.txt test2.txt 10 

我得到一个错误,表明输出文件存在,我检查了文件,即使我更改输出文件的名称(第二个参数),我也没有得到任何结果。 有谁可以提供帮助? 我现在多年来一直在绞尽脑汁。 这是我在Gentoo中编译和运行的UNIX作业。 我让它在VB中运行,并在我的Windows和Linux操作系统之间有一个链接文件夹。

 #include  #include  #include  #include  #include  #include  #define BUFFT 25 int main (int argc, char *argv[]) { int count; int readin; int writeout; printf ("This program was called \"%s\".\n",argv[0]); if (argc > 1) { for (count = 1; count < argc; count++) { printf("argv[%d] = %s\n", count, argv[count]); } } else { perror("The command had no arguments.\n"); exit(-1); } // check correct number of arguments parsed // if (argc == 4) { printf("There are the correct number of arguments(4)\n"); } else { perror("Not enough arguments! please try again \n"); exit(-1); } //Check original file is there// int openFD = open(argv[1], O_RDWR); if (openFD <0) { perror("Error unable to read file \n"); exit(-1); } //Check existence of output file, if it doesn't exist create it// int CheckFile = open(argv[2], O_RDONLY); if (CheckFile < 0) { perror("Error output file already exists \n"); exit(-1); } else { int CheckFile = open(argv[2], O_CREAT); printf("The file has successfully been created \n"); } //Create buffer int bufsize = atoi(argv[3]); char *calbuf; calbuf = calloc(bufsize, sizeof(char)); //Read text from original file and print to output// readin = read(openFD, calbuf, BUFFT); if (readin < 0){ perror("File read error"); exit(-1); } writeout = write(openFD,bufsize,readin); if (writeout <0){ perror("File write error"); exit(-1); } return 0; } 

HANDLE CheckFile打开调用正在打印错误文件存在 。 这是你的问题。 当您找不到输出文件时,您正在打印出错误的语句,而且您正在退出 ,这会阻止代码创建任何代码。

 int CheckFile = open(argv[2], O_RDONLY); if (CheckFile < 0) { //Means the file doesn't exist int CheckFile = open(argv[2], O_CREAT); // Check for errors here } 

你为什么要这样做::

 writeout = write(openFD,bufsize,readin); 

当你的输出文件手柄是CheckFile时

  int CheckFile = open(argv[2], O_RDONLY); if (CheckFile < 0) { perror("Error output file already exists \n"); 

open的负返回意味着无法打开文件,很可能是因为它不存在...这并不意味着该文件已经存在。 无法打开输入文件当然并不意味着输出文件已经存在。 请仔细检查您的代码是否存在明显的错误,例如:

 int CheckFile = open(argv[2], O_CREAT); printf("The file has successfully been created \n"); 

在这里,您不检查返回代码。

看一下代码的这个片段:

 int CheckFile = open(argv[2], O_RDONLY); if (CheckFile < 0) { perror("Error output file already exists \n"); exit(-1); } 

您正在尝试在READ ONLY MODE中打开文件。 从我在你的问题中读到的,如果文件不存在则不是错误,但是在validation相反的代码中,如果文件不存在,则抛出错误(实际上你的消息错误在这里是错误的) )。

仔细检查您的逻辑,您将找到您的解决方案。