c读写文件

#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);
}

  

posted on 2020-02-09 11:27  luckygxf  阅读(138)  评论(0编辑  收藏  举报

导航