2012-07-15 240 views
2

我想读一个指向文件中整型指针的指针。如何从文件读取指向整型指针的指针?

我使用下面的代码写入文件:

FILE *fp; 
int **myArray = NULL; 
int i, j; 

for(i = 0; i < 3; i++){ 
    myArray = (int **)realloc(myArray, (i+1)*sizeof(int *)); 
    for(j = 0; j < 4; j++){ 
     myArray[i] = (int *)realloc(myArray[i], (j+1)*sizeof(int)); 
     myArray[i][j] = i*j*10; 
    } 
} 

if((fp=fopen("test", "wb"))==NULL) { 
    printf("Cannot open file.\n"); 
} 
if(fwrite(myArray, sizeof(int), 3*4, fp) != 12) 
    printf("File write error."); 
fclose(fp); 

我使用下面的代码来读取,但我得到一个赛格故障在运行它。

FILE *fp; 
int **myArray = NULL; 
int i, j; 

for(i = 0; i < 3; i++){ 
    myArray = (int **)realloc(myArray, (i+1)*sizeof(int *)); 
    for(j = 0; j < 4; j++){ 
     myArray[i] = (int *)realloc(myArray[i], (j+1)*sizeof(int)); 
    } 
} 

if((fp=fopen("test", "rb"))==NULL) { 
    printf("Cannot open file.\n"); 
} 

if(fread(myArray, sizeof(int), 3*4, fp) != 12) { 
    if(feof(fp)) 
     printf("Premature end of file."); 
    else 
     printf("File read error."); 
} 

for(i=0; i < 3; i++){ 
    for(j = 0; j < 4; j++){ 
     printf("%d\n", myArray[i][j]); 
    } 
} 

fclose(fp); 

编辑:在更彻底的调试,我发现fread功能正在分配myArray无效的内存。关于我在这里可能做错了的任何想法?

+0

你绝对*不*阅读“指针指针”。你有什么是一个二维*数组*(你可能或不可以通过指针处理)。 – 2012-07-15 15:17:14

+3

@KerrekSB道歉。我正在发布整个问题。之前提交过错了。 – 2012-07-15 15:23:21

+0

@KerrekSB此外,我可能是错的,但不是这是一个指针指针“int”?当然,在大多数情况下,它的行为类似于2D阵列,但它不完全是一个。 – 2012-07-15 15:33:29

回答

1

从文件中读取指针(包括整数指针)是非常不寻常的。这是不常见的,因为文件中的信息在程序运行完成后仍然存在,但当程序结束时,操作系统会释放任何指针。

所以我假设你真正想要写(读)一些有用的数据(在你的情况整数),而不是指针 - 与你写代码不好:

FWRITE(myArray的,的sizeof(INT ),3 * 4,FP)

使用循环写入数据,而不是指针:

for(i = 0; i < 3; i++) 
{ 
    fwrite(myArray[i], sizeof(int), 4, fp); 
} 

然后,使用了类似的环来读取数据:

for(i = 0; i < 3; i++) 
{ 
    fread(myArray[i], sizeof(int), 4, fp); 
} 
1

如果使用putc()

char ch; 
FILE *input, *output; 
input = fopen("tmp.c", "r"); 
output = fopen("tmpCopy.c", "w"); 
ch = getc(input); 
while(ch != EOF) { 
    putc(ch, output); 
    ch = getc(input); 
} 
fclose(input); 
fclose(output); 

int矩阵现在更换*input。如果你得到一个segfault,这很可能是你没有正确分配内存。作为练习留给你。

+0

谢谢,使用'fwrite \ fread'有什么特别的错误吗? – 2012-07-15 15:31:25

+0

@stressed_geek不,没有错......但是当你每次插入一个'int'时听起来更自然。你也可以用你想输出的行格式创建一个字符串,然后'fwrite \ fread'会更有意义。 – cybertextron 2012-07-15 17:01:20

+0

@stressed_geek另外,如果它解决了你的问题,你能接受我的答案吗?因此,其他人可以稍后将其用作基准。 – cybertextron 2012-07-15 17:02:00