在基本反向文本C代码中接收分段错误

时间:2017-04-12 00:26:25

标签: c

我正在使用三个文件,我的reverse.c,file_utils.h和file_utils.c但是在成功编译并执行后我收到了一个Segmentation Fault(核心转储)。我不确定问题出在哪里。感谢您的任何意见!

Reverse.c文件:

#include "file_utils.h"
#include <stdio.h>
#include <sys/stat.h>
//reverse function
//calls two parameters for a pointer to the input file and a pointer to the output file
//outputs the input file into the output in reverse
int reverse(char* inputFile, char* outputFile) {
    char* buffer;
    read_file(inputFile, &buffer);
    struct stat st;
    stat(inputFile, &st);
    int size = st.st_size;

    write_file(outputFile, buffer, size);
}

int main(int argc, char** argv[]) {
    char* input;
    char* output;
    if(argv[1] != NULL) {
        input = argv[1];
    }
    else {
        printf("No input file detected.");
    }
    if(argv[2] != NULL) {
        output = argv[2];
    }
    else {
        printf("No output file detected.");
    }

    reverse(input, output);
}

file_utils.h标题:

#include <stdio.h>

void setup(int argc, char** argv);

int read_file( char* filename, char **buffer);
int write_file( char* filename, char *buffer, int size);

file_utils.c文件:

#include "file_utils.h"
#include "stdlib.h"

//read_file function has two parameters which call a pointer to the input filenmae and
//a pointer to the pointer where the buffer will be stored
//returns the pointer to the newBuffer
int read_file( char* filename, char **buffer ) {
    FILE *file;
    file = fopen(filename, "r");
    char* newBuffer = buffer;
    int c;
    size_t n = 0;

    if(file == NULL) {
        fprintf( stderr, "No file found. ");
        return -1;
    }
    // length of file code found on stackoverflow.com/questions/4823177/reading-a-file
    // given by user 'Justin'
    fseek(file, 0, SEEK_END);
    long f_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    buffer = malloc(f_size);
    if(newBuffer == NULL || newBuffer < 0) {
        fprintf(stderr, "Memory allocation error. ");
    }
    while((c = fgetc(file)) != EOF) {
        newBuffer[n++] = (char) c;
    }

    newBuffer[n] = '\0';

    return *newBuffer;
}
//write_file function has three parameters which consist of a pointer to the output file,
//the actual value of the buffer pointer, and the size of the buffer
int write_file( char* filename, char *buffer, int size) {
    fwrite(buffer, sizeof(char), size, filename);
}

0 个答案:

没有答案