标签:生成 fopen class null txt str printf sign span
文本文件,每行代表一个整数,范围在0~512之间;
要求:对文件排序,不使用堆空间,只使用栈空间。
用srand()和rand()函数生成一定量的随机数
/*** file.c ***/ #include<stdio.h> #include<string.h> #include<time.h> const int maxn = 100000; int main() { srand((unsigned int)time(NULL)); int i; FILE *p = fopen("./a.txt","w"); for(i = 0; i < maxn; i++) { fprintf(p,"%d\n",(int)rand() % 513); } fclose(p); return 0; }
然后排序:
/*** sort.c ***/ #include<stdio.h> #include<string.h> #include<time.h> int main() { int i; FILE *p = fopen("./a.txt","r"); int array[513] = {0}; while(!feof(p)) { char buf[100] = {0}; fgets(buf,sizeof(buf),p); if(0 != buf[0]) { int value = atoi(buf); array[value]++; } } fclose(p); p = fopen("./b.txt","w"); int j; for(i = 0; i < 513; i++) { for(j = 0; j < array[i]; j++) { fprintf(p,"%d\n",i); } } fclose(p); return 0; }
标签:生成 fopen class null txt str printf sign span
原文地址:https://www.cnblogs.com/wanghao-boke/p/11244828.html