|
Often the exact structure of a document is NOT know at the time it is read. Therefore, a function such as fscanf() cannot be used because the sequence, and type, of the data must be know beforehand! |
/* declare a file pointer */ FILE *infile; char *buffer; long numbytes; /* open an existing file for reading */ infile = fopen("test.rib", "r"); /* quit if the file does not exist */ if(infile == NULL) return 1; /* Get the number of bytes */ fseek(infile, 0L, SEEK_END); numbytes = ftell(infile); /* reset the file position indicator to the beginning of the file */ fseek(infile, 0L, SEEK_SET); /* grab sufficient memory for the buffer to hold the text */ buffer = (char*)calloc(numbytes, sizeof(char)); /* memory error */ if(buffer == NULL) return 1; /* copy all the text into the buffer */ fread(buffer, sizeof(char), numbytes, infile); fclose(infile); /* confirm we have read the file by outputing it to the console */ printf("The file called test.dat contains this text\n\n%s", buffer); /* free the memory we used for the buffer */ free(buffer); |
Once the buffer has been filled with a copy of the text from the source file it can used for operations such data extraction, searching/replacing and outputing to another file. More about that later! |
http://www.fundza.com/c4serious/fileIO_reading_all/index.html
'소프트웨어 > C' 카테고리의 다른 글
int * float 의 관계에 대해서 (0) | 2015.07.30 |
---|---|
scanf속에 표현식을 넣는 경우, scanf가 무시될 수 있다. (0) | 2015.07.29 |
struct 선언하면서 할당하기(?) _ struct의 이상한 모양 분석 (0) | 2015.06.10 |
[에러 리뷰] error: expected ‘,’ or ‘...’ before ‘this’ (0) | 2015.05.07 |
엔터(enter,개행문자) 입력받기. (0) | 2015.01.26 |