B Smith: 11/5/04. Lecture a 3. Fun for some, boring for others. Good lecture for introducing the idea of streams, so that in C++ ostream objects and istream objects are more intuitive. B Sm/5/04. Lecture a 3. Fun for some, boring for others. Good lecture for introducing the idea of streams, so that in C++ ostream objects and istream objects are more intuitive.
B Smith:
4/15/05: Rate: 3. The extra slides at end were not originally part of this. Incorporate these and discuss the keyboard input buffer and the residual \n
B Smith:
11/5: Finish up the last slide which discussed why EOF gets printed.
Math 130
#include <stdlib.h>
#include <stdio.h>
int main()
{
char descrip[10];
float price;
FILE *inFile;
inFile = fopen("prices.txt ","r");
if (inFile == NULL)
{
printf("\nFailed to open the file.\n");
exit(1);
}
while (fscanf(inFile,"%s %f",descrip,&price) != EOF)
printf("%-9s %5.2f\n",descrip,price);
fclose(inFile);
return 0;
}
Why/How does this work? (zoom in)
42 61 74 74 65 72 69 65-73 20 33 39 2E 39 35 0D Batteries 39.95.
0A 42 75 6C 62 73 20 20-20 20 20 20 33 2E 32 32 .Bulbs 3.22
0D 0A 46 75 73 65 73 20-20 20 20 20 20 31 2E 30 ..Fuses 1.0
33 0D 0A 00 00 00 00 00-00 00 00 00 00 00 00 00 3...............
fseek(inFile, 4L, SEEK_SET);
fseek(inFile, 4L, SEEK_CUR);
fseek(inFile, -4L, SEEK_CUR);
fseek(inFile, 0L, SEEK_SET);
fseek(inFile, 0L, SEEK_END);
fseek(inFile, -10L, SEEK_END);
Options for origin:
SEEK_SET – seek relative to start of file
SEEK_CUR – seek relative to current position
SEEK_END – seek relative to end of file
Options for offset:
The prototype specifies a long integer, and the value can be positive or negative
int main(int argc, char* argv[])
{
int i,j;
FILE * pFile;
pFile = fopen ("myfile.txt","w");
fputs ("This is an apple.",pFile);
fseek (pFile,9,SEEK_SET);
fputs (" sam",pFile);
fclose (pFile);
system("pause");
return EXIT_SUCCESS;
}
// After this code is executed, a file called example.txt
// will be created and will contain the sentence.
// “This is a sample.” (ref. cplusplus.com)
Where is the file ptr positioned? Why is EOF printed out and not CR/LF?
int main()
{
int ch, n;
long int offset, last;
FILE *inFile;
inFile = fopen("test.dat","r");
fseek(inFile,0L,SEEK_END); /* move to the end */
last = ftell(inFile); /* last = size of file */
for(offset = 0; offset <= last; ++offset)
{
fseek(inFile, -offset, SEEK_END); /* move to next character */
ch = getc(inFile); /* get the character */
switch(ch)
{
case '\n': printf("LF : ");
break;
case EOF : printf("EOF: ");
break;
default : printf("%c : ",ch);
break;
}
}
fclose(inFile);
return 0;
}pgm 11.5