Textdatei in Buffer einlesen
-
ich will eine Textdatei in einen Buffer einlesen - hab hier im Forum diesen Code gefunden
/* fread example: read a complete file */ #include <stdio.h> #include <stdlib.h> int main () { FILE * pFile; long lSize; char * buffer; pFile = fopen ( "myfile.txt" , "rb" ); if (pFile==NULL) exit (1); // obtain file size. fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); // allocate memory to contain the whole file. buffer = (char*) malloc (lSize); if (buffer == NULL) exit (2); // copy the file into the buffer. fread (buffer,1,lSize,pFile); /*** the whole file is loaded in the buffer. ***/ // terminate fclose (pFile); free (buffer); return 0; }
komischerweiße stehen am ende des Buffers komische Zeichen - hab mir die Textdatei mit nem HexEditor angesehen - da gabs die komischen Zeichen nicht
der Fehler tritt nur auf wenn man ein mehrzeiliges Textdokument hat - bei einer Zeile passiert noch nichts... mmhh...
-
0-Terminierung vergessen?
-
nö - hab ich net vergessen:
Textfile *newTextfile(char * Filename) { int iFileSize = getFileSize(Filename); Textfile *newTextfile = NULL; FILE * File = fopen(Filename, "rt"); newTextfile = malloc(sizeof(Textfile)); newTextfile->Buffer = malloc(iFileSize+1); fread(newTextfile->Buffer, iFileSize, 1, File); newTextfile->Buffer[iFileSize] = '\0'; // <= guckst du hier ;) fclose(File); return newTextfile; }
-
Hier was der Debugger sagt:
http://turing.fh-landshut.de/~jamann/txtproblem.PNGCode vom Bild:
/* fread example: read a complete file */ #include <stdio.h> #include <stdlib.h> int main () { FILE * pFile; long lSize; char * buffer; pFile = fopen ( "myfile.txt" , "rb" ); if (pFile==NULL) exit (1); // obtain file size. fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); // allocate memory to contain the whole file. buffer = (char*) malloc (lSize+1); if (buffer == NULL) exit (2); // copy the file into the buffer. fread (buffer,1,lSize,pFile); buffer[lSize] = 0; /*** the whole file is loaded in the buffer. ***/ // terminate fclose (pFile); free (buffer); return 0; }
-
Fehler gefunden!
int iFileSize = getFileSize(Filename); Textfile *newTextfile = NULL; FILE * File = fopen(Filename, "rt");
in getFileSize wird Dateigröße mit fopen(Filename, "rb") bestimmt - nachher wird mit "rt" eingelesen - dabei ist Unsinn rausgekommen ===> Problem gelöst