[英]Segmentation fault in comparing the second byte of two files
我正在測試命令fread()和fseek,我制作了一個程序來比較程序的第二個字節。 該程序在指示的行(最后一個fread())給出了分段錯誤。
int main(int argc, char** argv)
{
FILE *file1, *file2;
long size1, size2;
long size1a, size2a;
char *name1, *name2;
char *temp1, *temp2;
if (argc != 3)
{
cout<<"Enter two file names"<<endl;
exit(1);
}
name1 = argv[1];
name2 = argv[2];
//open files
file1 = fopen(name1, "r");
file2 = fopen(name2, "r");
//get file size
fseek(file1, 0, SEEK_END);
size1 = ftell(file1);
rewind(file1);
fseek (file2,0,SEEK_END);
size2 = ftell(file2);
rewind(file2);
fseek(file1,1,SEEK_SET);
fseek(file2,1,SEEK_SET);
cout<<"1"<<endl; //----cout worked
fread(temp1,1,1,file1);
cout<<"2"<<temp1<<endl; //---cout worked. 2nd byte of file1 was printed.
fread(temp2,1,1,file2); //SEGMENTATION FAULT AT THIS LINE
if(*temp1==*temp2)
cout<<"same"<<endl;
else
cout<<"different"<<endl;
return 0;
}
雖然我通過定義來糾正程序
char temp1, temp2;
和寫作
fread(&temp1,1,1,file1);
fread(&temp2,1,1,file2);
我仍然不知道是什么給了第二個fread的seg錯誤,而第一個運行正確。 可能是分段錯誤的原因是什么?
1)以二進制模式打開文件`fp = fopen(name,“rb”);
2)檢查文件打開的結果if(fp != NULL)
3)為數據分配內存: char *temp1;
是不夠的,它只是指針,你需要這樣的東西:
temp = (char*) malloc(sizeof(char) * N); // N number of bytes
編輯:
4)不要忘記關閉文件(即使它不是分段錯誤的原因)。
我只是進行更改,以下代碼可以正常工作:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
FILE *file1, *file2;
long size1, size2;
long size1a, size2a;
long greater;
char *name1, *name2;
char *temp1, *temp2;
// memory allocation (two lines added)
temp1 = (char*) malloc(sizeof(char));
temp2 = (char*) malloc(sizeof(char));
if (argc != 3)
{
cout<<"Enter two file names"<<endl;
exit(1);
}
name1 = argv[1];
name2 = argv[2];
//open files
file1 = fopen(name1, "rb");
if(file1 == NULL)
{
cout<<"File "<< name1 << " cannot be read" <<endl;
exit(1);
}
file2 = fopen(name2, "rb");
if(file2 == NULL)
{
cout<<"File "<< name2 << " cannot be read" <<endl;
exit(1);
}
//get file size
fseek(file1, 0, SEEK_END);
size1 = ftell(file1);
rewind(file1);
fseek (file2,0,SEEK_END);
size2 = ftell(file2);
rewind(file2);
if(size1>size2) greater = size1;
else greater = size2;
fseek(file1,1,SEEK_SET);
fseek(file2,1,SEEK_SET);
cout<<"1"<<endl; //----cout worked
fread(temp1,1,1,file1);
cout<<"2"<<temp1<<endl; //---cout worked. 2nd byte of file1 was printed.
fread(temp2,1,1,file2); //SEGMENTATION FAULT AT THIS LINE
if(*temp1==*temp2)
cout<<"same"<<endl;
else
cout<<"different"<<endl;
fclose(file1);
fclose(file2);
// memory de-allocation (two lines added)
free(temp1);
free(temp2);
return 0;
}
EDIT2:
5)使用后取消分配內存(增加兩行)
第一個版本的問題是temp
指針不指向任何東西:
char *temp1, *temp2;
...
fread(temp1,1,1,file1);
有了這個,文件中的字符被放置在temp
指針所指向的隨機位置。
對於第二個版本,字符放在temp
變量中,這沒關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.