【问题标题】:How do I use a FILE as a parameter for a function in C?如何使用 FILE 作为 C 中函数的参数?
【发布时间】:2013-03-22 04:59:16
【问题描述】:

我正在学习 C,我来自 Java 背景。如果我能得到一些指导,我将不胜感激。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    char *str = "test text\n";
    FILE *fp;

    fp = fopen("test.txt", "a");
    write(fp, str);
}

void write(FILE *fp, char *str)
{
    fprintf(fp, "%s", str);
}

当我尝试编译时,我得到了这个错误:

xxxx.c: In function ‘main’:
xxxx.c:18: warning: passing argument 1 of ‘write’ makes integer from pointer without a cast
/usr/include/unistd.h:363: note: expected ‘int’ but argument is of type ‘struct FILE *’
xxxx.c:18: error: too few arguments to function ‘write’
xxxx.c: At top level:
xxxx.c:21: error: conflicting types for ‘write’
/usr/include/unistd.h:363: note: previous declaration of ‘write’ was here

有什么想法吗?感谢您的宝贵时间。

【问题讨论】:

  • 我认为您正在调用系统调用write()。或许在main() 之上包含一个原型,更好的是,选择一个系统调用未使用的名称。
  • 你的函数没有问题,问题是选择的名称(unistd.h中使用了“write”)pubs.opengroup.org/onlinepubs/009695399/functions/write.html
  • 谢谢大家,对不起,让我们度过了一个漫长的夜晚。
  • 我认为你也可以使用 fwrite(str, 1, strlen(str), fp)。虽然效率不高。

标签: c file function unix


【解决方案1】:

您的函数缺少函数原型。此外,writeunistd.h 中声明,这就是您收到第一个错误的原因。尝试将其重命名为 my_write 或其他名称。您实际上也只需要 stdio.h 库作为旁注,除非您计划稍后使用其他功能。我添加了对 fopenreturn 0; 的错误检查,这应该结束 C 中的每个主要函数。

我会这样做:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

void my_write(FILE *fp, char *str)
{
    fprintf(fp, "%s", str);
}

int main(void)
{
    char *str = "test text\n";
    FILE *fp;

    fp = fopen("test.txt", "a");
    if (fp == NULL)
    {
        printf("Couldn't open file\n");
        return 1;
    }
    my_write(fp, str);

    fclose(fp);

    return 0;
}

【讨论】:

    【解决方案2】:

    在 Linux 上查看 man 2 write

    #include <unistd.h>
    
         ssize_t write(int fd, const void *buf, size_t count);
    

    这就是原型。您需要传递一个整数文件描述符而不是文件指针。 如果你想要自己的函数把名字改成foo_write什么的

    【讨论】:

      【解决方案3】:

      已经有一个名为write 的系统函数。只需将您的函数命名为其他名称,在使用之前添加一个函数声明,就可以了。

      【讨论】:

      • “你会没事的”——错了。函数必须在使用前声明。
      猜你喜欢
      • 2014-03-06
      • 2011-09-14
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      相关资源
      最近更新 更多