This a code that would reverse the data of a document and save it in the same document itself. However I am getting a Segmentation Fault.Please Help,I don't know why it gives a SegFault.
#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 I tried adding :
#include <sys/stat.h>
struct stat fs;
fstat(fd, &fs);
n= fs.st_size;
buf = malloc(n * sizeof (char));
but now it just duplicates the characters inside the document again and again instead of reversing them.