Would please somebody tell me why i constantly get coredump segmentation? when i choose n=1 work correctly but the problem is n=2 and n=3 but i have no idea why.I want to read a text file and return a text, binary or hex file.
I edited the code and i compile it and i get just one warning which is referring to %x but i do not care about it cause first i have to solve n==2. Now I do not have coredump error. it seems there is no error but my second file is empty.
int main(int argc, char *argv[])
{
if (argc != 3){
printf("Use this scheme: ./executabel read_file write_file -option(-b,-t,-x)\n");
exit(EXIT_FAILURE);
}
int fd1=open(argv[1], O_RDONLY);
int fd2=open(argv[2], O_WRONLY | O_CREAT);
char buffer[1024];
int rd_count = 0;
int wr_count = 0;
int n;
FILE * fpw;
fpw = fdopen (fd2, "w");
if (fd1 == -1){
printf("Failed to open the read-file.\n");
exit(EXIT_FAILURE);
}
if (fd2 == -1){
printf("Failed to open the write-file.\n");
exit(EXIT_FAILURE);
}
printf("Please choose one:\n");
printf("1. –t forces the output file to be a text one.\n");
printf("2. –b forces the output file to be binary.\n");
printf("3. –x forces the output file to be a hexadecimal representation.\n");
scanf("%d", &n);
while ((rd_count = read(fd1, (void*) buffer, 1024)) > 0){
int bytes_wr = 0;
while (bytes_wr != rd_count){
if (n==1){
wr_count = write(fd2, (void*) (buffer+bytes_wr), rd_count-bytes_wr);
}else if (n==2){
wr_count = fwrite( (void*) (buffer+bytes_wr), sizeof(float), rd_count-bytes_wr, fpw);
}else{
fprintf(fpw,"%x",(void*) (buffer+bytes_wr));
}
if (wr_count < 0) {
perror("Failed to write to file");
exit(EXIT_FAILURE);
} else {
bytes_wr += wr_count;
}
}
}
if (rd_count < 0) {
perror("Failed to read from file");
exit(EXIT_FAILURE);
}
close(fd1);
close(fd2);
chmod(argv[2],777);
exit(EXIT_SUCCESS);
}
By the way this is the warning
mahsa@mahsa-G53SW:~$ gcc -o ex4.o ex4.c -Wall -Wextra
ex4.c: In function ‘main’:
ex4.c:55:23: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘void *’ [-Wformat=]
55 | fprintf(fpw,"%x",(void*) (buffer+bytes_wr));
| ~^ ~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | void *
| unsigned int
| %p
I change this line
fprintf(fpw,"%x",(void*) (buffer+bytes_wr));
to this
fprintf(fpw,"%02x",buffer[bytes_wr]);
now i do not have even warning. it seems everything works correctly but when i open the second file is empty.