现在,我有这样的事情......
CMD控制台窗口: c:\users\用户名\Desktop> wrapfile.txt hello.txt
你好
我怎样才能得到这样的东西?
CMD控制台窗口: c:\users\用户名\Desktop> wrapfile.txt hello.txt hi.txt
你好你好
用这个代码?
#include <stdio.h>
#include <stdlib.h>
int main(int argc[1], char *argv[1])
{
FILE *fp; // declaring variable
fp = fopen(argv[1], "rb");
if (fp != NULL) // checks the return value from fopen
{
int i;
do
{
i = fgetc(fp); // scans the file
printf("%c",i);
printf(" ");
}
while(i!=-1);
fclose(fp);
}
else
{
printf("Error.\n");
}
}
最佳答案
好吧,首先:在你的 main
声明中,你应该使用 int main(int argc, char* argv[])
而不是你现在拥有的.在声明 extern
变量时指定数组大小没有意义(argv 和 argc 就是这样)。最重要的是,您没有使用正确的类型。 argc
是整数
,argv
是字符串数组
(它们是字符数组
).所以 argv
是一个由 char
组成的数组。
然后,只需使用 argc 计数器循环遍历 argv 数组。 argv[0]
是程序的名称,argv[1]
到 argv[n]
将是您传递给您的参数一边执行一边编程。
这里有一个关于它如何工作的很好的解释:http://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/#command-line
我的 2 美分。
编辑:这是工作程序的注释版本。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
FILE *fp;
char c;
if(argc < 3) // Check that you can safely access to argv[0], argv[1] and argv[2].
{ // If not, (i.e. if argc is 1 or 2), print usage on stderr.
fprintf(stderr, "Usage: %s <file> <file>\n", argv[0]);
return 1; // Then exit.
}
fp = fopen(argv[1], "rb"); // Open the first file.
if (fp == NULL) // Check for errors.
{
printf("Error: cannot open file %s\n", argv[1]);
return 1;
}
do // Read it.
{
c = fgetc(fp); // scans the file
if(c != -1)
printf("%c", c);
} while(c != -1);
fclose(fp); // Close it.
fp = fopen(argv[2], "rb"); // Open the second file.
if (fp == NULL) // Check for errors.
{
printf("Error: cannot open file %s\n", argv[2]);
return 1;
}
do // Read it.
{
c = fgetc(fp); // scans the file
if(c != -1)
printf("%c", c);
} while(c!=-1);
fclose(fp); // Close it.
return 0; // You use int main and not void main, so you MUST return a value.
}
希望对你有帮助。
关于c - 我怎样才能接受一个以上的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13753067/