Tuesday, 15 March 2011

c - I can't get fread() to print file content to a string variable -



c - I can't get fread() to print file content to a string variable -

i have been trying long time figure out how programme read text file. have tried solution fgets() , loop. programme runs not print variable, indicating text not extracted.

#include <stdio.h> #include <string.h> #include "stdfn.h" int main(int argc, char* argv[]) { char* request; char bf_text[1024]; char character; intro("site blocker", 2014, "mit"); request = bash("curl http://redsec.ru/blocked_sites.txt"); // source of bash() @ line 139 https://github.com/pavelovich/lib-c/blob/master/stdfn.h //printf("%s", request); file* block_file = fopen(".blocked_sites", "w+"); // changed "w" based on thread, outputs little part of file. file* hosts = fopen("hosts", "w"); file* hosts_tmp = fopen(".hosts", "w"); // print text of web request temporary // .blocked_sites file fprintf(block_file, "%s", request); rewind(block_file); fread(bf_text, sizeof(block_file), 1, block_file); printf("%s", bf_text); fclose(block_file); homecoming 0; }

sizeof(block_file) not give size of file. it'll give size of file pointer, either 4 or 8 bytes. 8 in case, since you're saying it's reading "74.125.2", 8 bytes, , going haywire. you'll need utilize stat() on posix system, or combination of fseek() , ftell().

you should open files in binary mode if you're going utilize fread() or fwrite(), since binary file io functions. won't create difference on unix systems, may on windows, instance. shouldn't mix text , binary mode io functions in way have reason.

you should checking returns fopen() calls create sure succeeded.

and bash() function you're using broken, too. you'll memory leak every time it's called because never free()s output, , it's making same sizeof error are, although it'll still work because of loop it's in. it'll waste memory allocated. , you leaking memory because never free(request). , you'd improve never #include in more 1 translation unit, either, unless want multiple definition errors on place. whole "library" riddled schoolboy-type errors, in fact, including repeated failures check homecoming malloc(), allocating memory fit pointer instead of thing it's pointing at, , on.

c fread

No comments:

Post a Comment