【问题标题】:Read input.txt file and also output.bmp file from terminal (C-programming)从终端读取 input.txt 文件和 output.bmp 文件(C 编程)
【发布时间】:2018-05-12 02:52:00
【问题描述】:

我必须做一个作业,我必须编写一个 C 程序,它从控制台获取输入文件名作为命令行参数。
它应该将数据从 input.txt 文件(输入文件包含 bmp 文件的信息 - 颜色等)移动到生成的 output.png 文件。 20 20 参数代表 output.png 图像的宽度和高度。

因此,例如控制台请求(在 Linux 上测试)将如下所示:

./main input.txt output.bmp 20 20

我知道这段代码读取了一个 input.txt 文件并将其放在屏幕上。

FILE *input;
int ch;
input = fopen("input.txt","r");
ch = fgetc(input);
while(!feof(input)) {
    putchar(ch);
    ch = fgetc(input);
}
fclose(input);

这将(例如)将其写入 output.png 文件。

FILE *output;
int i;
     output = fopen("ass2_everyinformationin.bmp", "wb+"); 
 for( i = 0; i < 55; i++)               
 {
     fputc(rectangle_bmp[i], output);
 }
 fclose(output);

但此代码仅在我直接在代码中硬编码名称时才有效,而不是通过使用命令行参数。
我没有任何线索,如何实现它,我也没有在互联网上找到任何有用的信息,也许有人可以帮助我。

问候

【问题讨论】:

  • 你知道 main() 的参数吗? IE。 argc 和 argv。
  • @Yunnosch 不,我不是……我需要他们得到想要的结果吗?
  • 不使用它们会很困难,使用它们很容易。一个告诉你你的程序有多少个参数,另一个代表一个数组,将它们作为“字符串”提供。查找不是以int main()int main(void) 开头的教程。
  • 非常感谢您的提示!你知道一个好的(和简单的)教程吗?

标签: c terminal console stdin fopen


【解决方案1】:

标准 main() 的完整原型是

int main(int argc, char* argv[]);

你会得到一个带有参数数量的 int,argc
“字符串”列表(只要它们存在于 C 中),argv

例如,您可以使用

#include "stdio.h"
int main(int argc, char* argv[])
{

    printf("Number: %d\n", argc);
    printf("0: %s\n", argv[0]);
    if (1<argc)
    {
        printf("1: %s\n", argv[1]);
    }
}

开始使用参数。

请注意,这不是有意实现的,而是使用命令行参数的基本示例。这符合公认的 StackOverflow 政策,即提供作业帮助,而无需解决它们。

【讨论】:

    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多