2013-06-01 140 views
9

如果我进入命令行 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./* 
+0

你用'fopen()'或'open()'打开它。 – Barmar

+0

是关于如何读取文件或关于如何从参数列表中获取文件名的问题? – Barmar

+0

请注意,如果您使用的是类似unix的系统,则可以将程序作为myprogram 来运行,并且该文件的内容将被输入到stdin中。 –

回答

11

您可以使用int main(int argc, char **argv)作为您的主要功能。

argc - 将是您的程序输入参数的计数。
argv - 将是一个指向所有输入参数的指针。

因此,如果您输入C:\myprogram myfile.txt运行程序:

  • argc将2
  • argv[0]myprogram
  • argv[1]将是myfile.txt

更多细节can be found here

读取文件:
FILE *f = fopen(argv[1], "r"); // "r" for read

对于其他模式,read this打开该文件。

+0

如何将'txt'文件名传递给另一个函数,而不是'main'? – Sigur

0

命令行参数只是普通的C字符串。你可以随心所欲地做任何事情。在你的情况下,你可能想打开一个文件,从中读取一些文件并关闭它。

你可能会觉得这个question(和答案)有用。

2
  1. 声明你的主这样

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

    • 的argc指定参数的个数(如果没有传递参数是等于1的程序的名称)

    • argv是一个指向字符串数组的指针(至少包含一个成员 - 程序名)

    • ,你会读通过命令行,像这样的文件:C:\my_program input_file.txt

  2. 建立一个文件句柄:

    File* file_handle;

  3. 打开file_handle阅读:

    file_handle = fopen(argv[1], "r");

    • 如果文件不存在,fopen会返回一个指向文件的指针或NULL。 ARGV 1,包含要读为参数的文件

    • “R”意味着您打开文件进行读取(更多在其它模式here

  4. 使用阅读内容例如fgets

    fgets (buffer_to_store_data_in , 50 , file_handle);

    • 你需要一个char *缓冲区存储在数据(如字符数组),第二个参数指定多少阅读和第三个是一个指向文件
  5. 最后关闭句柄

    fclose(file_handle);

全部完成:)

0

所有您收到有关使用命令行的建议是正确的,但 它的声音,我也可以考虑使用TY pical模式是读取stdin而不是文件,然后通过管道驱动您的应用,例如cat myfile > yourpgm。 然后您可以使用scanf从标准输入读取。 以类似的方式,您可以使用stdout/stderr来生成输出。

1

这是编程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 */ 
}