My last question作为背景。 我试图环绕“fopen()”,但 gcc 给了我这个错误,而“remove()”没有问题。
错误:“fopen”的类型冲突 fopen(const char *路径名, const char *模式) ^ 在 file_io_operation_interception.c:2:0 包含的文件中: /usr/include/stdio.h:272:14:注意:之前的“fopen”声明是 这里 extern FILE *fopen (const char *__restrict __filename,
这是代码。
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
static int (*real_fopen)(const char *pathname, const char *mode) = NULL;
static int (*real_remove)(const char *filename) = NULL;
static int (*real_close)(int fd) = NULL;
__attribute__((constructor))
void
my_lib_init(void)
{
real_fopen = dlsym(RTLD_NEXT,"fopen");
real_remove = dlsym(RTLD_NEXT,"remove");
real_close = dlsym(RTLD_NEXT,"close");
}
int
fopen(const char *pathname, const char *mode)
{
int fd;
// do whatever special stuff ...
fd = real_fopen(pathname, mode);
printf("open worked!\n");
char message[200];
char fidString[10];
sprintf(fidString, "%d ", fd);
strcat(message, fidString);
strcat(message, pathname);
sendMessage(message);
// do whatever special stuff ...
return fd;
}
int
remove(const char *filename)
{
int ret;
/*
if (real_remove == NULL)
real_remove = dlsym(RTLD_NEXT,"remove");
*/
// do whatever special stuff ...
printf("remove worked!\n");
sendMessage("remove message sent");
ret = real_remove(filename);
// do whatever special stuff ...
return ret;
}
int
close(int fd)
{
int ret;
/*
if (real_close == NULL)
real_close = dlsym(RTLD_NEXT,"close");
*/
// do whatever special stuff ...
printf("close worked!\n");
ret = real_close(fd);
// do whatever special stuff ...
return ret;
}
int
sendMessage(char *message)
{
int sockfd;
struct sockaddr_in servaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
int n, len;
sendto(sockfd, (const char *)message, strlen(message),
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
printf("message sent\n");
close(sockfd);
return 0;
}
“remove()”函数工作正常,但“fopen()”则不行。它们都在 stdio.h 中声明。但是,为什么会出现这种差异呢?
最佳答案
我已经找到解决办法了。 “fopen()”的返回值应该是FILE *,但我错误地使用了int。
关于c - 尝试覆盖 'fopen()' 但 GCC 给出 "error: conflicting types for ' fopen'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54249547/