這是一個可以反轉文檔數據並將其保存在同一文檔中的代碼。 但是我得到一個Segmentation Fault.Please幫助,我不知道它爲什麼會給出一個SegFault。爲什麼下面的代碼會引發SegFault? c(Linux)
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main (int argc,char* argv[])
{
int fd,n,i,j;
char* buf;
if(argc<2)
printf("USAGE: %s file-to-reverse.\n",argv[0]);
fd=open(argv[1], O_RDWR);
if(fd==-1)
printf("ERROR: Cannot reverse %s,file does not exist.\n",argv[1]);
i = 0;
j = n-1;
while(i < j)
{
read(fd,buf,n);
char ib = buf[i];
char jb = buf[j];
jb = i++;
ib = j--;
write(fd,buf,n);
}
free(buf);
close(fd);
}
EDIT1 我嘗試添加:
#include <sys/stat.h>
struct stat fs;
fstat(fd, &fs);
n= fs.st_size;
buf = malloc(n * sizeof (char));
,但現在它只是一遍又一遍,而不是 複製文檔裏面的人物倒他們。
除了答案「n」沒有在行「j = n-1;」中初始化。 – vobject 2010-09-05 19:46:01