所以这是我用过的第一个自编错误检查的程序之一,但是出于某种原因,当我编译它并使用它运行它时:
./file test1.txt test2.txt 10
我得到一个错误,表明输出文件存在并且我检查了文件,即使我更改输出文件的名称(第二个参数)也没有得到任何结果。有谁可以提供帮助?我现在已经绞尽脑汁了。这是我在Gentoo中编译和运行的UNIX作业。我让它在VB中运行,并在我的Windows和Linux操作系统之间有一个链接文件夹。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#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;
}
答案 0 :(得分:1)
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");
此处不检查返回代码。
答案 1 :(得分:1)
看一下代码的这个片段:
int CheckFile = open(argv[2], O_RDONLY);
if (CheckFile < 0)
{
perror("Error output file already exists \n");
exit(-1);
}
您正在尝试在READ ONLY MODE中打开文件。从我在你的问题中读到的,如果文件不存在则不是错误,但是在验证相反的代码中,如果文件不存在,则抛出错误(实际上你的消息错误在这里是不正确的) )。
仔细检查您的逻辑,您将找到解决方案。
答案 2 :(得分:1)
打开对 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
时