2016-04-14 91 views
-5

對不起,轉發。有另外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); 
} 

第二個,擁有的時候我會 「在參數錯誤」 運行

#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); 
} 
爲轉貼

對不起再次同樣的問題....

+0

,什麼是命令行? –

+0

輸入,輸出,錯誤信息,當您在調試器下運行時發現的內容,並逐步通過..... –

+1

最可能的原因是'argc <3'。 –

回答

3

你必須給你的程序3個參數。這是由此行引起的

if(argc < 3) { 

它表示「如果參數數目低於3」。

編輯:

此行是錯誤的,因爲你需要4個參數作爲程序名是第一個參數。此行更改爲

if(argc < 4) { 

並調用你的程序是這樣的:

./program file1 file2 file3 
+2

程序名稱在'argc'之間計數。 – EOF

+0

謝謝,我編輯。 – Boiethios

+0

我甚至沒有注意到訪問'argv [3]'的操作系統,很好的發現。 – EOF