【问题标题】:how to enter a function to a file in c如何在c中将函数输入到文件中
【发布时间】:2017-05-04 18:15:51
【问题描述】:

我在尝试输入 I/O 文件的代码中有此功能,但我似乎无法做到。

void show_list(int whyeven[stuff], char *hatred[stuff])
{
  for (int g = 0; g < stuff - 1; g++)
  {
    if (whyeven[g] < 10 || whyeven[g] == 0)
    {
      printf("%s    -   %d   (*)  you should buy more of this stuff\n\n",hatred[g], whyeven[g]);
    }
    else if (whyeven[g] > 10)
    {
      printf("%s   -    %d\n\n", hatred[g], whyeven[g]);
    }
  }
}

int main()
{
  show_list(moarstuff, items);
  return 0;
}

【问题讨论】:

  • 我们不知道它应该做什么以及它在做什么(和没有做什么)。请说清楚。另外,请提供minimal reproducible example
  • 为什么要测试whyeven[g] &lt; 10 || whyeven[g] == 0?第二个包含在第一个中。此外,您正在测试whyeven[g] &lt; 10 和稍后的whyeven[g] &gt; 10whyeven[g] == 10的时候呢?
  • 还有一点,尽管您认为自己是,但您并没有向您的函数发送 stuff

标签: c file io


【解决方案1】:

printf() 打印到 stdout。您需要 fopen() 该文件,然后使用 fprintf() 并将 fopen() 返回的 FILE* 指针作为第一个参数。

/* Open the file for writing */
FILE* fp = fopen("filename.txt", "w");
/* Check for errors */
if (fp == NULL)
{
    /* Notify the user of the respective error and exit */
    fprintf(stderr, "%s\n", strerror(errno));
    exit(1);
}
/* Write to the file */
fprintf(fp, "Hello!\n");
/* Close the file */
fclose(fp);

注意:你的问题很不清楚,这个答案是基于我能理解的。

【讨论】:

  • Generic this is how you do buffered file I/O 显然是在某个地方解决某个问题的 WAG - 但与 OP 的连接并不脆弱。
  • 我知道。我更喜欢更具体的问题。
猜你喜欢
  • 1970-01-01
  • 2021-04-03
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 2022-01-05
  • 1970-01-01
相关资源
最近更新 更多