评论

收藏

[C++] c读写文件

编程语言 编程语言 发布于:2021-08-07 14:07 | 阅读数:470 | 评论:0

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
char *fileName = "/Users/gxf/CLionProjects/untitled/text.txt";
void writeFile();
void readFile();
void fwriteFile();
void getChar();
void fputChar();
void putGetChar();
void freadfile();
typedef struct {
  int age;
  char *name;
} person;
#define BUFFSIZE 1024
int main() {
//  writeFile();
//  readFile();
  fwriteFile();
  freadfile();
//  getChar();
//  fputChar();
//  putGetChar();
  return 0;
}
void freadfile() {
  FILE *file2Read = fopen(fileName, "r");
  person p;
  int res = fread(&p, sizeof(person), 2, file2Read);
  if (res != 1) {
    perror("fread fail");
  }
  printf("person.age:%d, person.name:%s\n", p.age, p.name);
  fclose(file2Read);
}
void putGetChar() {
  while (1) {
    char ch = getchar();
    putchar(ch);
  }
}
void fputChar() {
  FILE *file2Write = fopen(fileName, "a+");
  char *msg2Write = "ffffffffffff";
  for (int i = 0; i < strlen(msg2Write); i++) {
    fputc(msg2Write[i], file2Write);
    printf("%c", msg2Write[i]);
  }
  fclose(file2Write);
}
void getChar() {
  FILE *file2Read = fopen(fileName, "r");
  char ch;
  while ((ch = fgetc(file2Read)) != EOF) {
    putchar(ch);
  }
}
void fwriteFile() {
  person zhangsan = {19, "name"};
  FILE *file2Write = fopen(fileName, "a+");
  fwrite(&zhangsan, sizeof(person), 1, file2Write);
  fclose(file2Write);
}
void readFile() {
  char buff[BUFFSIZE];
  FILE *file2Read = fopen(fileName, "r");
  while (fgets(buff, BUFFSIZE, (FILE *)file2Read) != EOF) {
    printf("buff:%s\n", buff);
    if(feof(file2Read))
      break;
  }
}
void writeFile() {
  FILE *file2Write = fopen(fileName, "a");
  fprintf(file2Write, "line1\n");
  fputs("line2\n", file2Write);
  fclose(file2Write);
}


关注下面的标签,发现更多相似文章