0

这是一个将反转文档数据并将其保存在同一文档本身中的代码。但是我遇到了分段错误。请帮忙,我不知道为什么它会给出分段错误。

#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));

但现在它只是一次又一次地复制文档中的字符,而不是反转它们。

4

4 回答 4

2

你不分配,也不初始化buf

于 2010-09-05T19:42:45.487 回答
2

您从未初始化n,因此它可能是任何东西,甚至是负面的。使用fstat或其他一些方法来确定文件的大小并将其存储在n.

于 2010-09-05T19:42:55.467 回答
2

您的缓冲区未分配且 n = 0,因此您将尝试读取 0 个字符。这应该修复您的代码:

buf = malloc(10 * sizeof (char));
n = 10;

资源 :

于 2010-09-05T19:43:14.190 回答
1

Regarding your second EDIT - your loop is wrong.

(1) Take the read & write out of the loop - that's why it keeps writing again & again.

(2) You need to seek back to the beginning of the file, otherwise you will just be appending the new data to the end of the file.

(3) You actually have to reverse the chars in the buffer before writing them out.

read(fd, buf, n);

while (i < j)
{

    char t = buf[i];

    buf[i] = buf[j];

    buf[j] = t;

    i++;
    j--;
}

lseek(fd, 0, SEEK_SET);

write(fd, buf, n);
于 2010-09-05T20:30:27.627 回答