Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在unix cp程序上检查EOF_Unix_Operating System_System Calls - Fatal编程技术网

在unix cp程序上检查EOF

在unix cp程序上检查EOF,unix,operating-system,system-calls,Unix,Operating System,System Calls,我正在编写一个unix cp程序,但我不清楚是否要检查EOF。我的密码是: int main(int argc, const char * argv[]) { int in, out; char buf[BUFFER_SIZE]; if (argc != 3) cout << "Error: incorrect number of params" << endl; if ((in = open(argv[1], O_RD

我正在编写一个unix cp程序,但我不清楚是否要检查EOF。我的密码是:

int main(int argc, const char * argv[]) {

    int in, out;
    char buf[BUFFER_SIZE];

    if (argc != 3)
        cout << "Error: incorrect number of params" << endl;
    if ((in = open(argv[1], O_RDONLY, 0666)) == -1)
        cout << "Error: cannot open input file" << endl;
    if ((out = open(argv[2], O_WRONLY | O_CREAT, 0666)) == -1)
        cout << "Cannot create output file" << endl;
    else
        while ((read(in, buf, BUFFER_SIZE)) != -1)
            write(out, buf, BUFFER_SIZE);


    return 0;
}
int main(int argc,const char*argv[]{
int-in,out;
char buf[缓冲区大小];
如果(argc!=3)

cout您应该阅读
read
功能的手册页

在文件末尾,
read
返回
0
。仅当出现错误时,才会返回
-1

read
可以读取的字节数少于您要求的字节数(如果没有那么多的字节需要读取,则必须这样做)。您的
write
调用假定
read
实际读取的
缓冲区大小
字节数

您需要保存由
read
返回的结果,并只写入那么多字节——并且当
read
返回
0
(表示文件结束)或
-1
(表示错误)时,您需要终止循环。在后一种情况下,您可能应该采取措施处理错误,或者至少通知用户


顺便说一下,调用
open
打开文件进行读取时,不需要
0666
模式参数;这仅适用于
O_create
。由于
open
实际上是一个可变函数(如
printf
),因此不必提供所有参数

在这一点上不清楚;它假装有两种不同形式的
open
功能:

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
但事实上,这在C中是不合法的。正确地将声明显示为:

int open(const char *path, int oflag, ...);

您应该阅读
read
功能的手册页

在文件末尾,
read
返回
0
。仅当出现错误时,才会返回
-1

read
可以读取的字节数少于您要求的字节数(如果没有那么多的字节需要读取,则必须这样做)。您的
write
调用假定
read
实际读取的
缓冲区大小
字节数

您需要保存由
read
返回的结果,并只写入那么多字节——并且当
read
返回
0
(表示文件结束)或
-1
(表示错误)时,您需要终止循环。在后一种情况下,您可能应该采取措施处理错误,或者至少通知用户


顺便说一下,调用
open
打开文件进行读取时,不需要
0666
模式参数;这仅适用于
O_create
。由于
open
实际上是一个可变函数(如
printf
),因此不必提供所有参数

在这一点上不清楚;它假装有两种不同形式的
open
功能:

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
但事实上,这在C中是不合法的。正确地将声明显示为:

int open(const char *path, int oflag, ...);

谢谢你的回答!我在阅读手册页时错过了read()的返回值。另外,0666参数修复了我在检查输出文件时遇到的一个恼人的默认文件权限错误。谢谢你的回答!我错过了read()的返回值当我阅读手册页时,0666参数还修复了我在检查输出文件时遇到的一个恼人的默认文件权限错误