c - 如何在 Ubuntu 中使用 "execute"Makefile 来运行从 stdin 读取并输出到 stdout/stderr 的 C 程序

标签 c makefile stdout stdin stderr

我正在解决一个家庭作业问题,该问题从 input.txt 文件中读取字符,并将读取的第一个单词输出到 output.txt 中,将第二个单词输出到error.txt,然后第三个再次output.txt,依此类推,直到到达input.txt 文件末尾。

我应该注意到这一切都是使用 Ubuntu 18.04 完成的

我得到了一个自定义 Makefile,并且必须编辑一个名为 split.c 的 C 程序,该程序将通过 stdin 获取 input.txt> 并输出到stdout/stderr。我可以编写我的 C 程序并将其列在下面,但是我无法测试它是否正确,因为我不明白如何运行 make、如何正确设置我的文件以及我的 C 程序是否正确读取和输出应该。

我尝试在终端中运行“make”命令,但收到:

make:未指定目标且未找到 makefile。停止。

我看过无数关于 Linux 的文章,制作“make 文件”等,但我不知道我被问到什么,也不知道该怎么做,所以我处于停滞状态。非常感谢指导!

自定义 makefile 如下所示,名为 Makefile.dat:

CC=gcc
CFLAGS=-Wall
EXEC=split
SRC=$(EXEC).c
TEXT_DIR=test
TEST_INPUT=$(TEST_DIR)/input.txt
OUT=$(TEST_DIR)/stdout.txt
ERR=$(TEST_DIR)/stderr.txt
EXP_OUT=$(TEST_DIR)/output.txt
EXP_ERR=$(TEST_DIR)/error.txt
TEST_REQS=$(TEST_INPUT) $(EXP_OUT) $(EXP_ERR)
DIFF=diff -bBqa

all:  $(EXEC)

$(EXEC): $(SRC)
   $(CC) $(CFLAGS) $(SRC) -o $(EXEC)

.PHONY: test
test: $(TEST_REQS) $(EXEC)
  ./$(EXEC) < $(TEST_INPUT) > $(OUT) 2> $(ERR)
  $(DIFF) $(EXP_OUT) $(OUT)
  $(DIFF) $(EXP_ERR) $(ERR)
  echo TEST PASSED!

.PHONY:  clean
clean:
  $(RM) $(EXEC)

我的 C 程序如下所示,名为 split.c:

#include <stdio.h>

int main(){
   int input;

   // keep getting characters until end-of-file
   while((input = fgetc(stdin)) != EOF){

     // prints to stdout
     printf(stdout, "%d", input);
     if(input = " ")
       printf("\n");    // encounters whitespace so print new line

     // prints to stderr
     printf(stderr, "%d", input);
     if(input = " ")
       printf("\n");    // encounters whitespace so print new line

    }

    return 0;

 }

其想法是,它获取输入文件,然后将每个字母打印到各自的文件中,如果遇到空格,它会在将下一个字符添加到另一个文件之前打印一个新行。

例如:

input.txt 包含文本:

"How do I do this stuff?"

output.txt 将包含:

 How
 I
 this

error.txt 将包含:

 do
 do
 stuff?

我完全预计我的 C 程序缺少代码。我编写程序时的想法是,打印到stdout,然后如果遇到空格,打印一个新行,然后开始打印到stderr,重复直到到达EOF。

最佳答案

Makefile.dat 重命名为 Makefile,如下所示:

mv Makefile.dat Makefile
make

或者使用 -f 选项和 Makefile 参数运行 make:

make -f Makefile.dat

确保所有文件(split.ctest/input.txtMakefile)都位于与Makefile,否则这将不起作用。

注意 C 代码的一些问题:

if(input = " ")

是错误的。首先,它将一个带有空格的字符串 "" (指向 char 的指针)分配给 input,而不是检查如果 input 是空格字符。

要解决此问题,请使用以下命令:

if(input == ' ')

在这两种情况下。

关于c - 如何在 Ubuntu 中使用 "execute"Makefile 来运行从 stdin 读取并输出到 stdout/stderr 的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57445808/

相关文章:

linux - 这个 Makefile 是如何工作的?

python - 在 os.dup2() 之后重定向标准输出/输入/错误

python - 为什么在控制台中写入 stdout 会附加写入的字符数,在 Python 3 中?

c - 将输入获取到动态分配的内存中,然后返回指针

c++ - C11 编译。翻译阶段 #1 和 #5。通用字符名称

c - 收到错误 : error: expected ')' before

c++ - makefile需要调用两次

c - 将 16 位有符号整数表示为 0-100 之间的值

c - 当我尝试构建时,Eclipse CDT 不使用我的 Makefile。

linux - JMeter 命令行 : Can I output the run log to STDOUT?