簡體   English   中英

C-通過命令行將輸入和輸出文本文件傳遞給我的程序

[英]C - pass an input and an output text file through command line to my program

我需要以命令行形式通過程序傳遞兩個文件

./your_executable inputfile.txt outputfile.txt

在我的示例中,我正在使用

gcc coursework.c CircleCode.txt CircleCode_tmp.txt

因此,第二個文件不存在,並在程序中打開了。

int main(int argc, char **argv[])
{
    FILE *orginalFile = fopen(*argv[1], "r");
    FILE *newFile = fopen(*argv[2], "w");

    if (orginalFile == NULL || newFile == NULL)
    {
        printf("Cannot open file");
        exit(0);
    }
}

Clang中的錯誤:

error: no such file or directory: 'CircleCode_tmp.txt'

您的main()簽名不正確。

可以將其更改為

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

要么

int main(int argc, char **argv)                                        

因為argv指向字符串數組。

看到這篇文章


由於需要程序的輸入和輸出文件才能工作,因此應檢查是否已接收到所需數量的參數。

argc將具有參數數量。 由於用於運行程序本身的命令名稱連同兩個文件一起計為一個參數,因此該程序至少需要3個參數。

所以你可能會做類似的事情

if(argc<3)
{                                                                        
   perror("Not enough arguments.");                                       
   return 1;                                                              
} 

還有

gcc coursework.c CircleCode.txt CircleCode_tmp.txt  

您要求編譯器也編譯您的輸入和輸出文本文件,這可能不是您想要的。

相反,你可以做

gcc -Wall coursework.c -o your_executable

編譯程序,然后像運行

./your_executable CircleCode.txt CircleCode_tmp.txt

gcc-Wall選項用於啟用一些警告,這些警告可能會更好地幫助您發現和更正錯誤。

也請參閱討論。

argv類型為char **,不需要[]

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
    FILE* orginalFile = fopen(argv[1], "r");
    FILE* newFile = fopen(argv[2], "w");

    if (orginalFile == NULL || newFile == NULL) {
      printf("Cannot open file");
      exit(0);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM