如何通过标准I/O技术而非命令行参数获取文件名

C语言 码拜 9年前 (2015-09-28) 865次浏览
 

Again, it is a simple matter to modify this program to use standard I/O techniques instead of command-line arguments to provide filenames.

C primer plus 只提了一下,说很简单,→_→ 

怎么弄额?

用 scanf ?用什么标识符?

还是用函数?

#3

回复2楼:

就一个简单的小程序 把一个文件中的内容复制到另一个文件中 

#4

10分

//赋值文本文件
#include <stdio.h>
int main(void)
{
	FILE *fi, *fo;
	fi = fopen("1.txt", "rb");
	fo = fopen("2.txt", "wb");
	char buf[128];
	while (1)
	{
		if (NULL == fgets(buf, sizeof(buf), fi)) break;
		fprintf(fo, "%s", buf);
	}
	fclose(fi);
	fclose(fo);
	return 0;
}
#5

10分

Again, it is a simple matter to modify this program to use standard I/O techniques instead of command-line arguments to provide filenames.

粗略地翻译一下,就是让你修改程序,使用标准I/O(技术)来提供文件名,而不是用命令行参数来提供文件名。

所谓的标准I/O,就是scanf这些东西了。

使用命令行提供文件名运行起来是这样的:

process.exe foo.txt

对于int main(int argc, char * argv[])来说,argv[1]即为”foo.txt”

使用I/O,运行起来就是这样:

cmd> process.exe

please input the file you want to process: foo.txt

所以代码中大概会有这样的语句:

char filename[80];

printf(“please input the file you want to process: “);

scanf(“%s”, filename);

process(filename):

所以说,英语也是一种语言。

#6

10分

#include <stdio.h>
#include <string.h>
#ifndef PATH_MAX
#define PATH_MAX    255
#endif
char *
strchop(char *s)
{
    size_t len;
    if (s) {
        len = strlen(s);
        if (len > 0 && (""\n"" == s[len - 1] || ""\r"" == s[len - 1]))
            s[len - 1] = ""\0"";
        len--;
        if (len > 0 && (""\n"" == s[len - 1] || ""\r"" == s[len - 1]))
            s[len - 1] = ""\0"";
    }
    return s;
}
int
main(int argc, char *argv[])
{
    char source[PATH_MAX] = {0};
    char target[PATH_MAX] = {0};
    if (1 == argc) {
        /* 通过标准 I/O 获取文件名 */
        printf("source: ");
        strchop(fgets(source, sizeof(source), stdin));
        printf("target: ");
        strchop(fgets(target, sizeof(target), stdin));
    } else {
        /* 通过命令行参数获取文件名 */
        strcpy(source, argv[1]);
        strcpy(target, argv[2]);
    }
    printf("source=[%s]\n", source);
    printf("target=[%s]\n", target);
    return 0;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明如何通过标准I/O技术而非命令行参数获取文件名
喜欢 (0)
[1034331897@qq.com]
分享 (0)