16

コマンド ライン 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./*
4

5 に答える 5

3

これがプログラミング 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 */ 
}
于 2013-06-01T05:56:17.403 に答える
0

stdinコマンドラインの使用についてあなたが受け取ったすべての提案は正しいですが、ファイルの代わりに読み込まれる典型的なパターンを使用することも検討できるように思えますmyfile > yourpgm。その後scanf、標準入力から読み取るために使用できます。同様の方法で、 を使用stdout/stderrして出力を生成できます。

于 2013-06-01T05:55:03.740 に答える