gpt4 book ai didi

c - 将文本写入多个c文件中的单个文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:38 25 4
gpt4 key购买 nike

我在多个文件中定义了函数。我想根据它们的执行情况将一些文本写入同一个文件,如下所示。我找到了在不同文件中编写执行流程的方法,如下所示。

function1.h

#ifndef FUNCTION1_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

int Sum(int a, int b);

#endif

function1.c

#include "function1.h"

int Sum(int a, int b)
{
FILE *fp;

fp = fopen("E:\\tmp\\test.txt", "a");
fputs("Inside Sum function...\n", fp);
fclose(fp);

return a+b;
}

ma​​in.c

#include "stdio.h"
#include "function1.h"

int main() {
int a=10, b=12;
FILE *fp;

fp = fopen("E:\\tmp\\test.txt", "a");
fputs("Before Sum function...\n", fp);
fclose(fp);

printf("%d + %d = %d", a, b, Sum(a, b));

fp = fopen("E:\\tmp\\test.txt", "a");
fputs("After Sum function...\n", fp);
fclose(fp);

}

当文件比较多时,上述方案很难处理。有没有直接的方法把test.txt写成多个*.c文件?

最佳答案

你可以打开一个文件并像参数一样传递它的描述符:

function1.h

#include <stdio.h>
#ifndef FUNCTION1_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

int Sum(int a, int b, FILE *f);

#endif

function1.c

#include "function1.h"

int Sum(int a, int b, FILE *f)
{
fputs("Inside Sum function...\n", f);
return a+b;
}

ma​​in.c

#include "function1.h"

int main() {
int a=10, b=12;
FILE *fp;

fp = fopen("E:\\tmp\\test.txt", "a");
fputs("Before Sum function...\n", fp);

printf("%d + %d = %d", a, b, Sum(a, b, fp));

fputs("After Sum function...\n", fp);
fclose(fp);

return 0;
}

关于c - 将文本写入多个c文件中的单个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51096843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com