c - 使用 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 文件的输出。怎么可能呢?
解决方案
为了运行 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);
此代码尚未经过测试。
推荐阅读
- python - 使用 url 作为参数时,opencv videocapture 如何工作?
- android - RecyclerView 宽度中的 TextView 溢出
- php - 如何只输入一个单词就可以访问链接?
- c - 如何使用 DisplayStringAtLine 函数在 STM32 上正确显示 uint32 变量
- spring-webflux - RSocket + webflux 请求-响应弹性
- ios - swift - 如何在 UITableView 的特定部分显示 xib?
- matlab - 在 matlab 中使用自行实现的霍夫线检测器可视化线条时需要帮助
- html - 如何使用 Bootstrap 在另一个 DIV 的左侧显示 DIV
- regex - 如何为路径编写正则表达式?
- javascript - 如何在 Angular 10 中获取下拉列表的新旧值