如果我进入命令行 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中。 –