2016-02-09 70 views
0

这里是我的代码 文件的名称filewrite.cFREAD错误 - 分段故障

#include<stdio.h> 
#include <stdlib.h> 
void main() 
{ 

    int *p; 
    *p = 5; 
    FILE *fp1 = fopen("sample.txt","w"); 
    fwrite(&p,sizeof(int),1,fp1); 
    fclose(fp1); 

    printf("\n Value of p written into the file is :%d \n",*p); 

int *q; 
FILE *fp2 = fopen("sample.txt","r"); 
fread(&q,sizeof(int),1,fp2); 
fclose(fp2); 

printf("\n Value of q read from the file is :%d \n",*q); 

} 

输出所看到的终端在Linux上:

$>gcc -o filewrite.o filewrite.c 

$>filewrite.o 

$>Segmentation fault (core dumped) 

我能看到文件sample.txt写出来。但无法理解为什么有一个核心转储。

+2

'p'和'q'不应该是指针。将它改为'int p = 5;'和'int q;'。 –

回答

0

您需要更改

fread(&q,sizeof(int),1,fp2); 

fread(q,sizeof(int),1,fp2); 

的第一个参数fread是一个void *和你传递一个pointer to pointer to int


而且,对于分配内存指针p

int *p; 
p = malloc(sizeof(int)); 

同样适用于q

int *q; 
q = malloc(sizeof(int)); 
+0

还有一个主要问题.... –

+0

我试过做你的改变。仍然我得到分段错误 – Sridhar

+0

@SouravGhosh,Thanx。编辑。 – Haris

0

在你的代码

int *p; 
*p = 5; 

调用undefined behavior当你试图写入未初始化的内存。没有明确的分配,p指向一些内存地址,这是最有可能不能从您的程序访问。

您需要先分配内存至p,然后才能对其进行解除处理。

也就是说,您使用fwrite()fread()是有问题的。您正在将指针指向int,而您需要将指针传递给void

如果您将pq的类型从int *更改为int,我相信这会解决您的问题。

这就是说,

  • void main()int main(void),至少,以符合标准。
  • 在使用返回的文件指针之前,请始终检查返回值fopen()是否为NULL以获得成功。
+0

嗨,非常感谢您的帮助,但我仍然面临问题,请检查我的代码一次。 。 void main() { int * p; p =(int *)malloc(sizeof(int)); * p = 5; FILE * fp1 = fopen(“sridhar.txt”,“w”); fwrite(&p,sizeof(int),1,fp1); fclose(fp1); (“\ n写入文件的p值为:%d \ n”,* p); int * q; FILE * fp2 = fopen(“sridhar.txt”,“r”); q =(int *)malloc(sizeof(int)); (q,sizeof(int),1,fp2); fclose(fp2); (“\ n从文件读取的q的值是:%d \ n”,* q);写入文件P的 } 值是:Q 5 值从文件中读取是:34000912 – Sridhar

+0

@Sridhar请不要急于....查看最新编辑我的答案。 –

+0

void main() { int * p; p =(int *)malloc(sizeof(int)); * p = 5; FILE * fp1 = fopen(“sridhar.txt”,“w”); fwrite(&p,sizeof(int),1,fp1); fclose(fp1); (“\ n写入文件的p值为:%d \ n”,* p); int * q; FILE * fp2 = fopen(“sridhar.txt”,“r”); q =(int *)malloc(sizeof(int)); (q,sizeof(int),1,fp2); fclose(fp2); (“\ n从文件读取的q的值是:%d \ n”,* q); } – Sridhar

0

正如你们建议的那样,我修改了我的代码,我能够得到正确的输出。 。非常感谢您的时间伙伴..守则

#include<stdio.h> 
#include <stdlib.h> 
int main() 
{ 

int *p; 
p = malloc(sizeof(int)); 
*p = 5; 
FILE *fp1 = fopen("sridhar.txt","w"); 
fwrite(p,sizeof(int),1,fp1); 
fclose(fp1); 

printf("\n Value of p written into the file is :%d \n",*p); 

int *q; 
FILE *fp2 = fopen("sridhar.txt","r"); 
q = malloc(sizeof(int)); 
fread(q,sizeof(int),1,fp2); 
fclose(fp2); 

printf("\n Value of q read from the file is :%d \n",*q); 

return 0; 
} 

输出为如下:

P的值写入该文件是:5 Q值从文件中读取的是:5个再次

感谢您的帮助@ Saurav和Haris

+0

而不是使用'malloc()',简单地不使用'int p'的原因是什么? –