c文件读写

文件读写

  • fprintf,fscanf

fprintf

#include <stdio.h>

int main(){
  int ar[] = {12,23,34,45,56,67,78,89,90,100};
  FILE* fp = NULL;
  fp = fopen("./text.txt","w");
  if(NULL == fp){
    printf("error\n");
  }
  for(int i = 0; i < sizeof(ar) / sizeof(int); ++i){
    printf("%d ", *(ar + i));
  }
  printf("\n");
  for(int i = 0; i< sizeof(ar) / sizeof(int); ++i){
    fprintf(fp, "%d", *(ar + i));
  }
  fprintf(fp,"\n");

  fclose(fp);
}

fscanf

#include <stdio.h>

int main(){
  FILE* fp = fopen("./text.txt", "r");
  if(NULL == fp){
    printf("error\n");
  }
  int ar[10];
  for(int i = 0; i < 10; ++i){
    fscanf(fp, "%d", (ar + i));
  }
  for(int i = 0; i < 10; ++i){
    printf("%d ",*(ar + i));
  }
  printf("\n");

  fclose(fp);
}

  • getc putc

putc

#include <stdio.h>
#include <string.h>

int main(){
  FILE *fp = fopen("./text1.txt", "w");
  if(NULL == fp){
    printf("error\n");
  }

  char cr[] = "getc putc";
  for(int i = 0; i < strlen(cr); ++i){
    putc(cr[i],fp);
  }
  putc('\n',fp);

  fclose(fp);
}

getc

#include <stdio.h>

int main(){
  FILE* fp = fopen("./text1.txt", "r");
  if(NULL == fp){
    printf("error/n");
    return 1;
  }

  char cr[9];
  char c;
  c = fgetc(fp);
  for(int i = 0;c != EOF; ++i){
    cr[i] = c;
    c = fgetc(fp);
  }
  for(int i = 0; i < 9; ++i){
    printf("%c", cr[i]);
  }
  printf("\n");


  fclose(fp);
}
  • puts gets

puts

#include <stdio.h>

int main(){
  FILE *fp = fopen("./text2.txt", "w");
  if(NULL == fp){
    printf("error\n");
    return 1;
  }
  char *s = "gets puts";
  fputs(s,fp);
  fputc('\n',fp);
  fclose(fp);
}

gets

#include <stdio.h>

int main(){
  FILE *fp = fopen("./text2.txt", "r");
  if(NULL == fp){
    printf("error\n");
    return 1;
  }
  char *s;
  fgets(s, 10,fp);
  printf("%s\n", s);
  fclose(fp);
}

sizfof, strlen的疑惑:https://www.cnblogs.com/zpcdbky/p/5857656.html

posted @ 2018-06-09 12:40  小石王  阅读(222)  评论(0编辑  收藏  举报