文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C语言 文件读写 定长记录

C语言 文件读写 定长记录

时间:2010-07-14  来源:btpka3

做个C项目,环境可能为Unix,要求 从/向 文件 读/写 定记录。
C啊,学过没用过,从大一学过到现在,哦,4年没碰过了。不过好歹自认为底子不错。先写个Sample练练手吧。

不过有一点,既然是定长记录。就应该定义一个结构体后,充分利用以下两个函数了:
    size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
    size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

但还有以下几对儿 从/向 文件 读/写 的函数啊??

    //但是,这一组是一个一个字符读写的,麻烦。
    int fgetc(FILE *stream);
    int fputc(int c, FILE *stream);
   
    //而这一组是一个字符串一个字符串读写的,可是需要自己预先排好格式
    int fputs(const char *s, FILE *stream); 
    char* fgets(char *s, int size, FILE *stream);

此外注意: sprinf() 函数会将字符串结尾符 '\0'(也即 NULL)赋值给第一个参数。

严重注意:使用结构体作为读写单位时,结构体内的数据必须是同一类型,否则可能会有数据对齐的问题,进而造成文件中的数据被一些乱码分隔。

运行结果:
fileIO.out.txt

--------------------------------writeRecordToFile()
Writing record to file succeed.
--------------------------------readRecordFromFile()
                 mp3F [email protected] std
                 mp4M [email protected] emp
                 mp5F [email protected] mgr
Reading record from file succeed.


源程序:
mytest001.h

/*
 * File: mytest001.h
 * Author: zhangll
 *
 * Created on 2010/07/07, 18:11
 */

#ifndef _MYTEST001_H
#define    _MYTEST001_H

#ifdef    __cplusplus
extern "C" {
#endif
    /*
    // What should be put in header files?
    // 1. External declaretions of global variables and functions.
    // 2. Preprocessor macro definirions.
    // 3. Structure definitions.
    // 4. Typedef declarations.
    //
    // What should NOT be put in header files?
    // 1. Defining instance of global variables.
    // 2. Funciton bodies.
     */
#define LEN_PERSON sizeof(Person)
#define LEN_PERSON_NAME (20)
#define LEN_PERSON_SEX (1)
#define LEN_PERSON_MAIL (20)
#define LEN_PERSON_AGE (3)
#define LEN_PERSON_JOB (10)

    typedef struct {
        unsigned char name [LEN_PERSON_NAME];
        unsigned char sex [LEN_PERSON_SEX];
        unsigned char mail [LEN_PERSON_MAIL];
        unsigned char age [LEN_PERSON_AGE];
        unsigned char job [LEN_PERSON_JOB];
        unsigned char end;
    } Person;

    /* sampe : file IO */
    extern void writeRecordToFile();
    extern void readRecordFromFile();

    extern void select01();
    extern void select02();
    extern void select03();

#ifdef    __cplusplus
}
#endif

#endif    /* _MYTEST001_H */


main.c

/*
 * File: main.c
 * Author: zhangll
 *
 * Created on July 6, 2010, 9:14 PM
 */

#include <stdlib.h>
#include "mytest001.h"

int main(int argc, char** argv) {
     writeRecordToFile();
     readRecordFromFile();
    /*select01();
    select02();
    select03();*/
    return (EXIT_SUCCESS);
}


FileIO.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mytest001.h"

char s_char_buf[LEN_PERSON + 1] = "\0";
int s_int_len = 0;
 
/*
 * write records to file
 */
void writeRecordToFile() {
    printf("--------------------------------writeRecordToFile()\n");

    /* 1. prepare data */
    Person personArr[3];

    /* clear the memory. not needed??? */
    memset(personArr, NULL, sizeof(Person) * 3);

    /* NOTICE : sprintf() will asign personArr[0].sex[0] to NULL;
     * so, the following asign sentense must following the order declared in
     * structure <Person>.
     */
    sprintf(personArr[0].name, "%20s", "mp3");
    sprintf(personArr[0].sex, "F");
    sprintf(personArr[0].mail, "%20s", "[email protected]");
    sprintf(personArr[0].age, "%03d", 25);
    sprintf(personArr[0].job, "%10s", "std");
    personArr[0].end = '\n'; /* NULL -> '\n' */

    sprintf(personArr[1].name, "%20s", "mp4");
    sprintf(personArr[1].sex, "M");
    sprintf(personArr[1].mail, "%20s", "[email protected]");
    sprintf(personArr[1].age, "%03d", 26);
    sprintf(personArr[1].job, "%10s", "emp");
    personArr[1].end = '\n';

    sprintf(personArr[2].name, "%20s", "mp5");
    sprintf(personArr[2].sex, "F");
    sprintf(personArr[2].mail, "%20s", "[email protected]");
    sprintf(personArr[2].age, "%03d", 27);
    sprintf(personArr[2].job, "%10s", "mgr");
    personArr[2].end = '\n';

    /* 2. open file */
    FILE* outFile = fopen("out_EN.txt", "wb");

    /* 3. open error check */
    if (NULL == outFile) {
        /* ERROR handle */
        perror("Unable open file for reading.\n");
    }

    /* 4. write records to file */
    int i = 0;
    int errFlag = 0;
    for (i = 0; i < 3; i++) {
        size_t writtenBytes = fwrite(&personArr[i], LEN_PERSON, 1, outFile);
        /* 4.1 IO error check */
        if (0 == writtenBytes) {
            /* ERROR handle */
            errFlag = 1;
            break;
        }
    }

    /* 5. close stream */
    fclose(outFile);

    /* 6. message */
    if (errFlag) {
        perror("Error occured while writing record to file.\n");
    } else {
        printf("Writing record to file succeed.\n");
    }
}

void readRecordFromFile() {
    printf("--------------------------------readRecordFromFile()\n");
    Person p;

    /* 1. open file */
    FILE* inFile = fopen("out_EN.txt", "rb");

    /* 2. open error check */
    if (NULL == inFile) {
        /* ERROR handle */
        perror("Unable open file for reading.\n");
    }

    /* 3. read records from stream */
    int errFlag = 0;
    size_t readBytes = 0;
    readBytes = fread(&p, LEN_PERSON, 1, inFile);
    while (0 != readBytes) {
        /* 3.1 handing records(here just print it to stdout) */
        p.end = NULL; /* '\n' -> NULL */
        printf("%s\n", (char *)&p);

        readBytes = fread(&p, LEN_PERSON, 1, inFile);
    }
    
    /* 3.2 IO error check */
    if (ferror(inFile)) {
        /* ERROR handle */
        errFlag = 1;
    }

    /* 4. close stream */
    fclose(inFile);

    /* 5. message */
    if (errFlag) {
        perror("Error occured while reading record from file.\n");
    } else {
        printf("Reading record from file succeed.\n");
    }
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载