我现在有函数代码,当我试图从文件到数组的转换中生成函数时,我得到了一个分割错误。我知道里面的东西
fileToArray
是正确的(只要
myData
因为在函数内部,
myData.length
和
myData.array
全部正确返回。但是,在主指针被引用之后,我得到一个seg错误。我是C新手,但所有这些都是在没有指向结构的特定指针的情况下工作的。
所以,如果我用一个带有多行文本的文件的参数调用这个程序,就会发生set错误。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
typedef struct {
int length;
char** array;
} FileStruct;
void fileToArray(FileStruct* fileDataPtr, int argc, char *argv[]){
int fd, i, n, count;
struct stat statbuf;
char *buf, *inbuf, *str, *saveptr;
char **array;
if ((fd = open(argv[1], O_RDONLY)) == -1) {
printf("Error opening file %s\n", argv[1]);
exit (-1);
}
if (lstat(argv[1], &statbuf) < 0) {
printf("Unable to lstat file %s\n", argv[1]);
exit (-1);
}
off_t filesize = statbuf.st_size;
buf = malloc(sizeof(char)*filesize);
array = malloc(sizeof(char *)*filesize);
count = 0;
if ((n = read(fd, buf, filesize)) > 0){
inbuf = buf;
for (i = 1; ; inbuf = NULL, i++) {
str = strtok_r(inbuf, "\n", &saveptr);
if (str == NULL)
break;
array[count] = malloc(sizeof(char)*(strlen(str)+1));
strcpy(array[count++], str);
}
} else {
printf("Error reading input file\n");
exit (-1);
}
close(fd);
for (i = 0; i < count; i++) {
printf("%s\n", array[i]);
free(array[i]);
}
fileDataPtr->length = count;
fileDataPtr->array = array;
free(array);
free(buf);
}
int main(int argc, char *argv[]) {
int i;
FileStruct myData;
FileStruct* fileDataPtr = &myData;
fileToArray(fileDataPtr, argc, argv);
printf("length: %i", myData.length);
return 0;
}