2

最近开始使用指针并创建了一个小脚本,应该将一些文本文件拼接在一起。

但是,当我尝试调用 fputs 时,我得到一个核心转储/分段错误。我怀疑这是因为文件指针的保存方式。我发现文件将其保存在一个数组中,并稍后尝试检索它。

FILE 指针保存在结构中。有人会立即发现我的错吗?我会很感激!

结构:

typedef struct{
int listSize;
int listCapacity;
FILE *fileStream;
}FileList;

创建结构

FileList fileList;
fileList.listSize=0;
fileList.listCapacity=1;
fileList.fileStream=calloc(fileList.listCapacity,sizeof(FILE));

然后我通过调用将结构添加到数组中

void addFile(FileList* list, FILE* file)
{
    list->fileStream[list->listSize]=*file;
}

但是,当我打电话时

char* buffer[10];
size_t result=0;

result = fread(buffer,1,10,&fileList.fileStream[ii+currentGroupOffset]);
    fputs(*buffer,outPutFile);

它崩溃了,我试图观察值 ii+currentGroupOffset 确保它不会超出数组范围

有任何帮助!:)

4

3 回答 3

1

It seems you want a dynamically allocated array of FILE* elements. You have:

FILE *fileStream;

That can either be treated as a FILE pointer, or an array of FILE elements. But not as an array of FILE pointers. For that, you need:

FILE **fileStream;

And allocating the array should be done with:

fileList.fileStream=calloc(fileList.listCapacity,sizeof(FILE*));

FILE is not a type you use directly. You always deal with pointers to it. You should treat it as an opaque type.

Also, I don't see where you actually open the files (using fopen()) anywhere in your code.

于 2012-11-13T00:11:20.907 回答
1

Why

char * buffer[10];

It should be

char buffer[10];

Where is list->listSize incremented?

I don't understand what this is

 fileList.fileStream=calloc(fileList.listCapacity,sizeof(FILE));

FILE *s are initialized by calling fopen not by allocating memory

于 2012-11-13T00:13:53.950 回答
1

您不能自己分配和复制FILE结构 - 它是一种不透明的数据类型。因此,与其创建一个FILE结构数组,不如创建一个FILE *指针数组:

typedef struct {
    int listSize;
    int listCapacity;
    FILE **fileStream;
} FileList;

FileList fileList;

fileList.listSize = 0;
fileList.listCapacity = 1;
fileList.fileStream = calloc(fileList.listCapacity, sizeof fileList.fileStream[0]);

然后FILE *通过复制指针值来添加指向数组的指针:

void addFile(FileList *list, FILE *file)
{
    list->fileStream[list->listSize] = file;
}

并像这样使用它:

char buffer[10];
size_t result = 0;

result = fread(buffer, 1, 10, fileList.fileStream[ii+currentGroupOffset]);
fwrite(buffer, 1, result, outPutFile);
于 2012-11-13T00:18:04.230 回答