Portál AbcLinuxu, 9. května 2025 02:48
Access not within mapped region at address 0x0 ==26680== at 0x3BD606CD90: fwrite (in /usr/lib64/libc-2.17.so)Je mozne, ze se nekdy nejak nekorektne otevre soubor pro psani? Premyslim, v cem to muze byt. Lze kod nejak osetrit tak, aby to bylo vzdy korektni?
void send_file(char *source, char *destination) { FILE * filer, * filew; int numr, numw; char buffer[1024]; if ((filer = fopen(source, "rb")) == NULL) { perror("open read file error.\n"); //exit(1); } if ((filew = fopen(destination, "wb")) == NULL) { perror("open write file error.\n"); //exit(1); } while (feof(filer) == 0) { if ((numr = fread(buffer, 1, 100, filer)) != 100) { if (ferror(filer) != 0) { perror("read file error.\n"); //exit(1); } else if (feof(filer) != 0); } if ((numw = fwrite(buffer, 1, numr, filew)) != numr) { perror("write file error.\n"); //exit(1); } } fclose(filer); fclose(filew); }
Řešení dotazu:
A nejsou právě problémem ty zakomentované exit-y?, tedy dle hlášky zrovna ten ve fopen pro filew.
U zapisovaného souboru je dobré kontroloval návratový kód fclose, moc se to sice nedělá, ale…
#include <stdlib.h> #include <unistd.h> #include <stdio.h> void send_file(const char *source, const char *destination) { FILE * filer, * filew; int numr; const int SIZE_OF_BUFFER=1024; char buffer[SIZE_OF_BUFFER]; if ((filer = fopen(source, "rb")) == NULL) { perror("open read file error.\n"); exit(1); } if ((filew = fopen(destination, "wb")) == NULL) { perror("open write file error.\n"); fclose(filer); exit(1); } while (feof(filer) == 0) { if ((numr = fread(buffer, 1, SIZE_OF_BUFFER, filer)) != SIZE_OF_BUFFER) { if (ferror(filer) != 0) { perror("read file error.\n"); fclose(filer); fclose(filew); exit(1); } } if (fwrite(buffer, 1, numr, filew) != numr) { perror("write file error.\n"); fclose(filer); fclose(filew); exit(1); } } if(fclose(filer) != 0) printf("read file - close error.\n");//has read-file been deleted ... ??? if(fclose(filew) != 0) printf("write file - close error.\n");//flush C buffer fails //fsync ???? } int main( int argc, const char* argv[] ){ if (argc == 3 ) { send_file(argv[1], argv[2]); } else { printf("Main error, two params needed (from, to).\n"); return 1; } return 0; }
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.