从C程序创建命令行应用程序

时间:2016-03-28 20:49:23

标签: c

如何将此程序(binary.c)转换为命令行应用程序,以便它可以读取任何二进制文本(例如binary1.txt)文件,然后将其转换为ASCII?例如,我想做:

./binary < binary1.txt 

它应该打印

  

Hello World!

在命令行。

这是我的计划:

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *f_ptr;
f_ptr = fopen("binary1.txt", "r");
if (f_ptr == NULL){
printf("Error opening binary1.txt");
return 1;
}

while(1){
int ch = fgetc(f_ptr);
if(ch == EOF)
break;

printf("%c",ch);

}

fclose(f_ptr);
return 0;
}

3 个答案:

答案 0 :(得分:0)

我不确定你在问什么。我想你需要使用编译器编译源代码。如果您使用Linux,则可以执行:gcc binary.c -o binary以获取可执行文件...

答案 1 :(得分:0)

#include <stdio.h>

int main(int argc, char *argv[]){
    FILE *fp;
    if(argc < 2)//./binary < binary1.txt
        fp = stdin;
    else {//./binary  binary1.txt
        if((fp=fopen(argv[1], "r")) == NULL){
            perror("fopen");
            return 1;
        }
    }
    int ch, count = 0;
    unsigned char out = 0;
    while((ch = fgetc(fp))!=EOF){
        if(ch == '1' || ch == '0'){
            out <<= 1;
            out += ch - '0';
            if(++count == 7){//7bit code
                printf("%c", out);
                count = out = 0;
            }
        }
    }
    puts("");
    fclose(fp);
    return 0;
}

答案 2 :(得分:-2)

据我所知,您正在尝试将文件名传递给您的程序而不确定如何执行此操作。在这种情况下,您可能想要这样做

int main(int argc, char* argv[])
{
  if(argc>1)
  std::string filename = argv[1];
  //now you have the file in the filename

 // your code 
 return 0;
}

所以当你执行时只需执行此操作

./binary binary1.txt

您不需要使用<,我假设您的可执行文件和文本文件都位于同一目录中

相关问题