如果我在命令行中输入了以下命令:
C: myprogram myfile.txt
我该如何在程序中使用myfile呢?是否需要使用scanf读取它,还是有其他任意访问的方法?
我的问题是如何在程序中使用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呢?是否需要使用scanf读取它,还是有其他任意访问的方法?
我的问题是如何在程序中使用myfile.txt文件。
int
main(){
/* So in this area how do I access the myfile.txt
to then be able to read from it./*
txt
文件名传递给另一个函数,而不是传递给 main
函数? - Sigur声明main函数如下:
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);
完成啦 :)
这是编程入门的方法。它假设了很多内容,并且没有进行任何错误检查!但它可以帮助你开始。
/* 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 */
}
stdin
而不是文件,然后通过管道驱动你的应用程序,例如 cat myfile > yourpgm
。
然后你可以使用scanf
从标准输入中读取数据。
类似地,你可以使用stdout/stderr
来产生输出。
fopen()
或open()
打开它。 - Barmarmyprogram < myfile
,文件的内容将被输入到stdin中。 - John Carter