-1

这段代码编译得很好并且运行完美,直到我尝试打印出缓冲区。我在网上找到了很多资源,但我无法解决我的问题!我真的很感激另一只眼睛。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int store_file(char* file_dir, char* buffer)
{
    FILE* file;
    long lSize;
    size_t result;
    int i;
    char* tempBuffer;

    file = fopen(file_dir, "r");
    if (file==NULL)
    {
        fputs("File error.", stderr);
        exit(1);
    }

    fseek(file, 0, SEEK_END);
    lSize = ftell(file);
    rewind(file);

    tempBuffer = (char*)malloc(sizeof(char)*lSize);
    if (tempBuffer == NULL)
    {
        fputs("Memory error.", stderr);
        exit(2);
    }

    result = fread(tempBuffer, 1, lSize, file);
    if (result != lSize)
    {
        fputs("Reading error.", stderr);
        exit(3);
    }

    buffer = tempBuffer;
    free(tempBuffer);
    fclose(file);
    return sizeof(buffer);
}

void fsa_cycle(char* file_dir)
{
    char* buffer;
    int bufferSize = store_file(file_dir, buffer);
    char n;

    // This is the line that generates the issue.
    // I have also tried printf("%s",buffer); but that also doesn't work.
    fwrite(buffer, sizeof(char), bufferSize, stdout);
}

int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        printf("\nSyntax: %s <file-name>\n\n", argv[0]);
        exit(1);
    }

    fsa_cycle(argv[1]);
}

任何建议都会很棒!我知道答案很愚蠢。但是我作为一个初学者很难自己理解。感谢您的帮助。

4

1 回答 1

1

你的问题是它int store_file(char* file_dir, char* buffer)不会改变原始buffer指针,只会改变它的副本。要进行更改buffer,您需要将指针传递给它:

int store_file(char* file_dir, char** buffer)
// whenever referring to it, use *buffer instead of buffer
// e.g. *buffer = tempBuffer;

并这样称呼它:

int bufferSize = store_file(file_dir, &buffer);
于 2013-07-16T19:22:59.640 回答