Terrible coder here, this program I'm trying is to take user input and return it reversed in a new file. the kicker is using system calls (which I have just been exposed to). I am having trouble with my outputs. May someone please point out the error?
#include <fcntl.h>
#include <stdio.h>
#include "apue.h"
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main(){
int fd1;
int fd2;
int offset;
char readc;
char filename[125];
printf("Please enter the file you wish to reverse: ");
scanf("%s", &filename);
fd1 = open(filename, O_RDONLY);
printf("open succesfully! File has been reversed and in a new file\n");
if (fd1 < 0) { perror("Error! Can't open file\n"); exit(1); }
//create a new file
fd2 = open("ReversedFile.txt", O_RDWR | O_CREAT, 0644);
if(fd2 < 0){ perror("Error! Can't open file"); exit(1); }
offset = lseek(fd1, 0, SEEK_END);
while(offset > 0){
read(fd1, &readc, 1);
write(fd2, &readc, 1);
lseek(fd1, -2, SEEK_CUR);
offset--;
}
close(fd1);
close(fd2);
return 0;
}
My first output where foo.txt contained exclamation points (which are invalid i discovered) is:
\00World Hello
!gnidoc ta kcus I
if this is readable i am correct
My second output however without exclamation point is:
圀牯摬䠠汥潬朊楮潤慴欠畣晩琠楨獩爠慥慤汢浡挠牯敲瑣
Why is this happening?