欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c文件读写

程序员文章站 2022-07-04 23:05:21
文件读写 fprintf,fscanf fprintf gets sizfof, strlen的疑惑:https://www.cnblogs.com/zpcdbky/p/5857656.html ......

文件读写

  • 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的疑惑: