Read from a file (.txt) and save into a char* C -
i have file.txt contais, example, "this txt file" (this content can variable) , need function reads file.txt , save content char*.
file.txt contains -> "this .txt file"
and need char *readedcontent contains "this .txt file".
first, save content of char *str (str contains "this .txt file") "file.txt" , try string file string have more chars "this .txt file". (often add characters spaces or @,?)
my function is:
char *special_char_remplace(char *str){ file *f1; f1 = fopen("file.txt","w+"); fprintf(f1,"%s", str); fclose(f1); size_t len, bytesread; char *readedcontent; file* f2; f2 = fopen("file.txt", "rb"); fseek(f2, 0, seek_end); len = ftell(f2); rewind(f2); readedcontent = (char*) malloc(sizeof(char) * len + 1); readedcontent[len] = '\0'; // needed printing stdout printf bytesread = fread(readedcontent, sizeof(char), len, f2); printf("string: %s\n", readedcontent); fclose(f2); return readedcontent; }
the problem have in char *readedcontent have more chars file.txt's content.
thanks much.
the problem have in
char *readedcontent
have more charsfile.txt
's content.
the reason why more bytes there characters in file encoding of file: fread()
reads file byte-for-byte, if file's encoding uses multiple bytes code points, buffer going contain multiple bytes 1 or more characters.
to verify theory , fix problem, write short program writes bytes of intended message, "this .txt file"
, text file using fwrite()
api. file written in way should read correctly fread()
.
Comments
Post a Comment