Posts
文件读写

文件读写

记录了C语言的文件IO

在python中 f = open("file.txt", 'r') 读取文件单行 f.readline() 读取多行 f.readlines()

whole_txt

char *fgetls(FILE *fp){
    // pointer locate to file end
    fseek(fp, 0L, SEEK_END);
    // total length of file.txt
    long length = ftell(fp);
    // reset pointer for file head
    rewind(fp);
    char *whole_text = xcalloc(1, length + 1);
    if(1 != fread(whole_text, length, 1, fp)){
      free(whole_text);
      fprintf(stderr, "fread failed"), exit(1);
    }
    return whole_text;
}

single_line

char *fgetl(FILE *fp){
  if(feof(fp)) return 0;
  size_t size = 512;
  char *line = xmalloc(size * sizeof(char));
  if(!fgets(line, size, fp)){
    free(line);
    return 0;
  }
  
  size_t cur = strlen(line);
  // when alloc size insufficient, 2 times realloc
  while((line[cur-1] != '\n') && !feof(fp)){
    if(cur == size - 1){
      size *= 2; 
      line = xrealloc(line, sizeof(char) * size);
    }
    size_t read_size = size - cur;
    // overflow
    if(read_size > INT_MAX) read_size = INT_MAX - 1;
    fgets(&line[cur], read_size, fp);
    cur = strlen(line);
  }
  
  // delete \r\n
  if(cur >= 2)
    if(line[cur - 2] == 0x0d) line[cur - 2] = 0x00;
  if(cur >= 1)
    if(line[cur - 1] == 0x0a) line[cur - 1] = 0x00;
  return line;
}

fgets读行,遇 \nfeof返回字符串,并添加\0 fread读块,feof返回

Updated at