日期:2014-05-16 浏览次数:20754 次
#include <stdio.h> #include <stdlib.h> struct stock { char name[20]; int price; }; int main() { FILE *file; file = fopen("./stockInfo.txt", "r"); if(file == NULL) { printf("open file failed!\n"); exit(-1); } struct stock buffer; while(!feof(file)) { fscanf(file, "%s %d", buffer.name, &buffer.price); printf("%s %d", buffer.name, buffer.price); } return 0; }
while(!feof(file)) /*fscanf到达文件尾时,并没有立刻执行feof(file), *而是在printf之后才去检测是否到达文件尾的. *因此会再一次输出buffer的内容 *而你也没有在读到buffer里面前memset, *所以最后一条会重复输出 */ { fscanf(file, "%s %d", buffer.name, &buffer.price); printf("%s %d", buffer.name, buffer.price); } while(1) { memset(&buffer,0x00,sizeof(struct stock)); fscanf(file, "%s %d", buffer.name, &buffer.price); if(feof(file))break;/*到达文件尾立刻跳出*/ printf("%s %d\n", buffer.name, buffer.price); }