用C实现文件readLine函数

/ ReadWord.cpp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"

#define MAX 64


bool readword(FILE *fp,char words[])
{
 if(fp==NULL) 
 {
  puts("The file is not exist!");
  return false;
 }
 if(feof(fp))
 {
  puts("The end of the file!");
  return false;
 }

 *words='\0';
 char vChar=getc(fp);
 while(vChar!=EOF&&vChar!='\n')
 {
  *(words++)=vChar;
  *words='\0';
  vChar=getc(fp);
 }
 return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
 FILE *fp;
    char words[MAX];
    int i=1;
 /* 
 //used to create file content
 if ((fp = fopen("testFile", "a+")) == NULL)
 {
  fprintf(stdout,"Can't open \"testFile\" file.\n");
  exit(1);
 }
 puts("Enter words to add to the file; press the Enter key at the beginning of a line to terminate.");
 while (gets(words) != NULL  && words[0] != '\0')
  fprintf(fp, "%s ", words);
    puts("File contents:");
    rewind(fp);           /// go back to beginning of file 
    while (fscanf(fp,"%s",words) == 1)
        puts(words);*/

    
    if((fp=fopen("testFile","r"))==NULL)
 {
  fprintf(stdout,"Can't open \"testFile\" file.\n");
  exit(1);
 }
 
 while(readword(fp,words))
 {
  printf("Line %d:",i++);
  puts(words);
 }
 rewind(fp);

 if (fclose(fp) != 0)
        fprintf(stderr,"Error closing file\n");

 return 0;
}

 

你可能感兴趣的:(数据结构-编程算法-技术思想)