繁体   English   中英

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

[英]Write text to the single text file in multiple c files

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

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;
}

main.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);

}

当存在多个文件时,上述解决方案很难处理。 是否可以直接在多个* .c文件中写入test.txt

将文件指针作为参数int Sum(int a, int b, File *F)传递int Sum(int a, int b, File *F)然后(最后)可以查找SEEK_SET以返回文件的开头。

您可以打开文件并像参数一样传递其描述符:

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;
}

main.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;
}
#include <stdio.h>
#include <stdlib.h>

/* Define SHOW_WHERE to turn on show_where() */
#define SHOW_WHERE

#ifdef SHOW_WHERE

#define show_where(fp) \
    fprintf(fp, "FILE=%s\tLINE=%d\tFUNC=%s\tDATE=%s\tTIME=%s\n", __FILE__, __LINE__, __FUNCTION__,  __DATE__, __TIME__); \
    fflush(fp);

#else

#define show_where(fp)

#endif

int main(int argc, char *argv[])
{
    show_where(stdout);

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM