首页 > 试题广场 >

使用命令行参数的程序要求用户记住正确的使用方法。重写程序清单

[问答题]
使用命令行参数的程序要求用户记住正确的使用方法。重新编写下面的程序,不使用命令行参数,而是提示用户键入所需的信息。
// reducto.c -- 把您的文件压缩为原来的三分之一!
#include <stdio.h>
#include <stdlib.h>    // 为了调用exit()
#include <string.h>    // 为strcpy()和strcat()函数提供原型
#define LEN 40
int main (int argc, char *argv[])
{
    FILE *in, *out;        // 声明两个FILE指针
    int ch;
    char name[LEN];        // 用于存储输入文件名
    int count = 0;
// 检查命令行参数
if(argc < 2)
    {
       fprintf(stderr, "Usage: %s filename\n", argv[0]);
       exit(1);
    }
// 实现输入
if ((in = fopen(argv[1], "r")) == NULL)
    {
       fprintf(stderr, "I couldn't open the file \"%s\"\n",
               argv[1]);
       exit(2);
    }
// 实现输出
    strcpy(name, argv[1]);  // 把文件名复制到数组中
    strcat(name, ".red");   // 在文件名后添加.red
    if((out = fopen (name, "w")) == NULL)
    {                      // 打开文件以供写入
        fprintf(stderr, "Can't create output file.\n");
        exit(3);
    }
// 复制数据
    while ((ch = getc(in)) != EOF)
        if (count++ % 3 == 0)
            putc(ch, out);  // 打印每3个字符中的1个
// 收尾工作
    if(fclose (in) != 0 || fclose (out) != 0)
       fprintf(stderr, "Error in closing files\n");
    return 0;
}
推荐
// reducto.c -- reduces your files by two-thirds!
#include <stdio.h>
#include <stdlib.h>    // for exit()
#include <string.h>    // for strcpy(), strcat()
#define LEN 40
int main(void)
{
 FILE  *in, *out;   // declare two FILE pointers
 int ch;
 char name[LEN];    // storage for output filename
 int count = 0;
// set up input
 puts("Enter the name of the file to be reduce");
 gets(name);
 if ((in = fopen(name, "r")) == NULL)
 {
 fprintf(stderr, "I couldn't open the file \"%s\"\n",
 name);
 exit(2);
 }
// set up output
 name[LEN - 5] = '\0';
 strcat(name,".red");            // append .red
 if ((out = fopen(name, "w")) == NULL)
 {                       // open file for writing
 fprintf(stderr,"Can't create output file.\n");
 exit(3);
 }
// copy data
 while ((ch = getc(in)) != EOF)
 if (count++ % 3 == 0)
 putc(ch, out);  // print every 3rd char
// clean up
 if (fclose(in) != 0 || fclose(out) != 0)
 fprintf(stderr,"Error in closing files\n");
 return 0;
}

发表于 2018-05-05 22:01:36 回复(0)