我在分配时遇到问题,我必须将一个文件的内容放入缓冲区,反转这些内容,然后将它们写入另一个文件。该程序需要使用两个如下所示的函数:
int read_file( char* filename, char **buffer );
int write_file( char* filename, char *buffer, int size);
到目前为止,我的文件如下所示:
文件实用程序.h
#ifndef UTILS_H
#define UTILS_H
int read_file(char* filename, char **buffer);
int write_file(char* filename, char *buffer, int size);
#endif
文件实用程序.c
#include "file_utils.h"
#include <stdlib.h>
#include <stdio.h>
#include <font1.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int read_file(char* filename, char **buffer) {
FILE* file1;
file1 = fopen(filename, "r");
//gets the size of the file
struct stat st;
stat(filename, &st);
int size = st.st_size;
buffer = malloc(size);
read(file1, &buffer, 1);
return size;
}
int write_file(char* filename, char*buffer, int size) {
FILE* file2;
file2 = fopen(filename, 'w');
for (int k = size - 1; k >= 0; k--) {
char* x = &buffer + k;
fprintf(file2, "%s", x);
}
printf(filename, '\O');
return 1;
}
反向.c
#include "file_utils.h"
#include <stdlib.h>
#include <stdio.h>
#include <font1.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
char* buffer;
char* filename1;
char* filename2;
int filesize;
filename1 = argv[1];
filename2 = argv[2];
filesize = read_file(filename1, &buffer);
write_file(filename2, buffer, filesize);
return 0;
}
这就是全部。我使用“clang file_utils.c reverse.c”运行它,我收到类似 file_utils.c 的警告
incompatible integer to pointer conversion passing 'int" to parameter of type 'const char *'
(对于行 file1 = fopen(filename, 'r')incompatible pointer to integer conversion passing 'FILE *' (aka 'struct_IO_FILE*') to parameter of type 'int'
(对于 read(file1, &buffer, 1);)- 与第一个警告相同,但针对 file2 = fopen(filename, 'w');
- 和
incompatible pointer types initializing 'char *' with an expression of type 'char **'; dereferences with *
(对于 char* x = &buffer + k; 行)
最重要的是,当我继续运行可执行文件时
./a.out file1 file2
其中文件 1 的文本应该反转到文件 2 中,我得到一个分段错误。
对我可以解决的问题的任何见解将不胜感激。