如果我進入命令行 C:myprogram myfile.txt的的命令行參數,讀取文件
我怎麼能在我的程序中使用MYFILE。我必須掃描它還是有一個任意的訪問方式。
我的問題是如何在我的程序中使用myfile.txt。
int
main(){
/* So in this area how do I access the myfile.txt
to then be able to read from it./*
如果我進入命令行 C:myprogram myfile.txt的的命令行參數,讀取文件
我怎麼能在我的程序中使用MYFILE。我必須掃描它還是有一個任意的訪問方式。
我的問題是如何在我的程序中使用myfile.txt。
int
main(){
/* So in this area how do I access the myfile.txt
to then be able to read from it./*
命令行參數只是普通的C字符串。你可以隨心所欲地做任何事情。在你的情況下,你可能想打開一個文件,從中讀取一些文件並關閉它。
你可能會覺得這個question(和答案)有用。
聲明你的主這樣
int main(int argc, char* argv [])
的argc指定參數的個數(如果沒有傳遞參數是等於1的程序的名稱)
argv是一個指向字符串數組的指針(至少包含一個成員 - 程序名)
,你會讀通過命令行,像這樣的文件:C:\my_program input_file.txt
建立一個文件句柄:
File* file_handle;
打開file_handle閱讀:
file_handle = fopen(argv[1], "r");
使用閱讀內容例如fgets:
fgets (buffer_to_store_data_in , 50 , file_handle);
char *
緩衝區存儲在數據(如字符數組),第二個參數指定多少閱讀和第三個是一個指向文件最後關閉句柄
fclose(file_handle);
全部完成:)
所有您收到有關使用命令行的建議是正確的,但 它的聲音,我也可以考慮使用TY pical模式是讀取stdin
而不是文件,然後通過管道驅動您的應用,例如cat myfile > yourpgm
。 然後您可以使用scanf
從標準輸入讀取。 以類似的方式,您可以使用stdout/stderr
來生成輸出。
這是編程101的方式。這需要很多理所當然的事情,它根本不會做任何錯誤檢查!但它會讓你開始。
/* this has declarations for fopen(), printf(), etc. */
#include <stdio.h>
/* Arbitrary, just to set the size of the buffer (see below).
Can be bigger or smaller */
#define BUFSIZE 1000
int main(int argc, char *argv[])
{
/* the first command-line parameter is in argv[1]
(arg[0] is the name of the program) */
FILE *fp = fopen(argv[1], "r"); /* "r" = open for reading */
char buff[BUFSIZE]; /* a buffer to hold what you read in */
/* read in one line, up to BUFSIZE-1 in length */
while(fgets(buff, BUFSIZE - 1, fp) != NULL)
{
/* buff has one line of the file, do with it what you will... */
printf ("%s\n", buff); /* ...such as show it on the screen */
}
fclose(fp); /* close the file */
}
你用'fopen()'或'open()'打開它。 – Barmar
是關於如何讀取文件或關於如何從參數列表中獲取文件名的問題? – Barmar
請注意,如果您使用的是類似unix的系統,則可以將程序作爲myprogram來運行,並且該文件的內容將被輸入到stdin中。 –