参数错误..

时间:2016-04-14 12:19:07

标签: c

对不起重新发布。有另外2个代码和1个问题。这两个代码都会向我显示"参数错误"当我打算跑他们的时候。

第一个代码 -

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/file.h>
main (argc, argv)
int argc;
char *argv[];
{
    int fd1, fd2, fd3;
    int nbytes, mode, nbytes1;
    char buf[BUFSIZ];
    if(argc < 3) {
            fprintf(stderr, "%s: Error in parametrs\n", argv[0]);
    exit(1);
    }
    if ((fd1 = open(argv[1], O_RDONLY)) < 0 ) {
            fprintf(stderr, "Can`t open file %s\n",
            argv[1]);
    exit(1);
    }
    if ((fd2 = open(argv[2],O_WRONLY | O_CREAT, mode)) < 0) {
            fprintf(stderr, "Can`t create new file %s\n", argv[2]);
            exit(1);
    }
    if ((fd3 = open(argv[3], O_WRONLY | O_CREAT, mode)) < 0) {
            fprintf(stderr, "Can`t create new file %s\n", argv[3]);
            exit(1);
    }

    while((nbytes = read(fd1, buf, BUFSIZ))> 0) {
            if(write(fd2, buf, nbytes) < 0) {

            fprintf(stderr, "Write error\n"); break;
           }
            if(write(fd3, buf, nbytes) < 0) {

            fprintf(stderr, "Write error\n"); break;
           }

    }



    if(nbytes < 0) fprintf(stderr, "Reading error\n");
    close(fd1);
    close(fd2);
    close(fd3);
    exit(0);
}

第二个,当我要运行它时会遇到同样的问题&#34;参数错误&#34;

#include <unistd.h>
#include <sys/file.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>
main (argc, argv)
int argc;
char *argv[];
{
    int fd1, fd2, fd3;
    int nbytes, mode, nbytes1;
    char buf[BUFSIZ];
    if(argc < 3) {
            fprintf(stderr, "%s: Error in parametrs\n", argv[0]);
    exit(1);
    }
    if ((fd1 = open(argv[1], O_RDONLY)) < 0 ) {
            fprintf(stderr, "Can`t open file %s\n",
            argv[1]);
    exit(2);
    }
    if ((fd2 = open(argv[2],O_WRONLY | O_CREAT, mode)) < 0) {
            fprintf(stderr, "Can`t create new file %s\n", argv[2]);
            exit(3);
    }
    if ((fd3 = open(argv[3], O_WRONLY | O_CREAT, mode)) < 0) {
            fprintf(stderr, "Can`t create new file %s\n", argv[3]);
            exit(4);
    }

    while((nbytes = read(fd1, buf, BUFSIZ))> 0) {
            if(write(fd2, buf, nbytes) < 0) {

            fprintf(stderr, "Write error\n");
            break;
           }
            if(write(fd3, buf, nbytes) < 0) {

            fprintf(stderr, "Write error\n");
            break;
           }

    }



    if(nbytes < 0) fprintf(stderr, "Reading error\n");
    close(fd1);
    close(fd2);
    close(fd3);
    exit(0);
}

再次抱歉重新发布....

1 个答案:

答案 0 :(得分:3)

你必须给你的程序3个参数。这是由此行引起的

if(argc < 3) {

表示&#34;如果参数数量低于3&#34;。

编辑:

这一行是错误的,因为你需要4个参数,因为程序名是第一个参数。将此行更改为

if(argc < 4) {

以这种方式打电话给你的程序:

./program file1 file2 file3
相关问题