|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
建立两个磁盘文件f1.dat和f2.dat,编程序实现以下工作:
① 从键盘输入20个整数,分别存放在两个磁盘文件中(每个文件中放10个整数);
② 从fl.dat中读入10个数,然后存放到f2.dat文件原有数据的后面;
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- void write_2_files(int *nums, int count, FILE *first, FILE *second) {
- for (int i = 0; i < count; i++) {
- if (0 == (i & 1)) {
- fprintf(first, "%d ", nums[i]);
- } else {
- fprintf(second, "%d ", nums[i]);
- }
- }
- }
- char *read_all(FILE *f, long *length) {
- fseek(f, 0L, SEEK_END);
- *length = ftell(f);
- fseek(f, 0L, SEEK_SET);
- char *result = (char *) malloc(sizeof(char) * (*length + 1));
- memset(result, 0, sizeof(char) * (*length + 1));
- fread(result, sizeof(char), *length, f);
- return result;
- }
- char *read_ints(int count, FILE *from) {
- long length = 0;
- char *buffer = read_all(from, &length);
- int begin = 0, end = 0;
- for (begin = 0; begin < length; begin++) {
- char curr = buffer[begin];
- if (curr >= '0' && curr <= '9') {
- break;
- }
- }
- int found = 0;
- for (int i = begin + 1; i < length; i++) {
- char prev = buffer[i - 1];
- char curr = buffer[i];
- if (curr == ' ' && prev >= '0' && prev <= '9') {
- found += 1;
- }
- if (found >= count) {
- end = i;
- break;
- }
- }
- buffer[end] = '\0';
- char *result = strdup(buffer + begin);
- buffer[end] = ' ';
- free(buffer);
- return result;
- }
- void read_and_append_ints(int count, FILE *to, FILE *from) {
- char *buffer = read_ints(count, from);
- fprintf(to, " %s", buffer);
- free(buffer);
- }
- void foo(int *nums, const char *expected, int count) {
- FILE *first = fopen("f1.dat", "w+");
- FILE *second = fopen("f2.dat", "w+");
- write_2_files(nums, count, first, second);
- read_and_append_ints((count + 1) / 2, second, first);
- long length = 0;
- char *result = read_all(second, &length);
- if (0 != strcmp(expected, result)) {
- printf("result: %s, expected: %s\n", result, expected);
- }
- free(result);
- }
- int main() {
- {
- int array[] = {1};
- foo(array, " 1", sizeof(array) / sizeof(array[0]));
- }
- {
- int array[] = {1, 2};
- foo(array, "2 1", sizeof(array) / sizeof(array[0]));
- }
- {
- int array[] = {1, 2, 3};
- foo(array, "2 1 3", sizeof(array) / sizeof(array[0]));
- }
- {
- int array[] = {1, 2, 3, 4};
- foo(array, "2 4 1 3", sizeof(array) / sizeof(array[0]));
- }
- {
- int array[20] = {0};
- for (int i = 0; i < sizeof(array) / sizeof(array[0]); i++) {
- array[i] = i;
- }
- foo(array,
- "1 3 5 7 9 11 13 15 17 19 0 2 4 6 8 10 12 14 16 18",
- sizeof(array) / sizeof(array[0]));
- }
复制代码
|
|