现在的位置: 首页 > 综合 > 正文

读写文件

2018年05月18日 ⁄ 综合 ⁄ 共 821字 ⁄ 字号 评论关闭
c语言读写文件实例,读大量数据时据说还是c语言效率高,比c++的fstream快...留存。

#include <stdio.h>
#include <stdlib.h>
FILE *f;
int i;
int v;
int n;
int m[100000];
int compare(const void *a,const void *b) {
    return (*((int *)a)) - (*((int *)b));
}
int main() {
    f=fopen("D:\\number.txt","r");
    if (NULL==f) {
        printf("Can not find file D:\\number.txt!\n");
        return 1;
    }
    i=0;
    while (1) {
        if (feof(f)) break;
        if (1==fscanf(f,"%d",&v)) {
            m[i]=v;
            i++;
            if (i>=100000) break;
        else {
            fscanf(f,"%*c");
        }
    }
    fclose(f);
    n=i;
    qsort(m, n, sizeof(int), compare);
    f=fopen("D:\\result.txt","w");
    if (NULL==f) {
        printf("Can not create file D:\\result.txt!\n");
        return 1;
    }
    for (i=0;i<n;i++) fprintf(f,"%d\n",m[i]);
    fclose(f);
    return 0;
}

抱歉!评论已关闭.