首页 > 解决方案 > 使用 C 中的文件处理程序执行 hello.c 文件

问题描述

我最近在用 C 试试运气,我遇到了这个我被困住的问题。

我有一个 hello.c 文件

代码 1

#include<stdio.h>
#include<stdlib.h>
int main(){
    printf("Hello World");
    return 0;
}

我打开此文件并使用以下 C 程序(代码 2)显示内容

代码 2

#include<fcntl.h>
#include<stdio.h>    
int main() {

    FILE *fd;
    char ch;
    fd = fopen("/home/hello.c","r");

    if( fd != NULL ) {
        while((ch = getc( fd )) != EOF){
                putchar(ch);
        }
    }

    return 0;
}

但是,我希望这段代码的输出是 Hello World,即读取的 hello.c 文件的输出。怎么可能呢?

标签: cfile-handling

解决方案


为了运行 ac 文件,首先你需要将它编译成机器码然后执行它。

编译它:运行 gcc source-file -o executable-file

要运行,请执行:executable-file

为了在 C 中做同样的事情,使用system()函数 from<stdlib.h>

const char* tempFile = "./tempfile";
const char* sourceFile = "hello.c";

const char compileCommand[255];
sprintf(compileCommand, "gcc %s -o %s", sourceFile, tempFile);

system(compileCommand);

system(tempFile);

此代码尚未经过测试。


推荐阅读