【发布时间】:2010-09-05 19:40:24
【问题描述】:
此代码将反转文档的数据并将其保存在同一文档本身中。 但是我遇到了分段错误。请帮忙,我不知道为什么会出现分段错误。
#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;”行初始化。
标签: c linux ubuntu segmentation-fault file-descriptor