gpt4 book ai didi

c - 如何使用 FILE 作为 C 函数的参数?

转载 作者:太空狗 更新时间:2023-10-29 14:57:35 26 4
gpt4 key购买 nike

我正在学习 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

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

最佳答案

您的函数缺少函数原型(prototype)。此外,write 是在 unistd.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;
}

关于c - 如何使用 FILE 作为 C 函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15738029/

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