急!求指导思路或者解答
建立两个磁盘文件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);
} else {
fprintf(second, "%d ", nums);
}
}
}
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;
if (curr >= '0' && curr <= '9') {
break;
}
}
int found = 0;
for (int i = begin + 1; i < length; i++) {
char prev = buffer;
char curr = buffer;
if (curr == ' ' && prev >= '0' && prev <= '9') {
found += 1;
}
if (found >= count) {
end = i;
break;
}
}
buffer = '\0';
char *result = strdup(buffer + begin);
buffer = ' ';
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));
}
{
int array[] = {1, 2};
foo(array, "21", sizeof(array) / sizeof(array));
}
{
int array[] = {1, 2, 3};
foo(array, "21 3", sizeof(array) / sizeof(array));
}
{
int array[] = {1, 2, 3, 4};
foo(array, "2 41 3", sizeof(array) / sizeof(array));
}
{
int array = {0};
for (int i = 0; i < sizeof(array) / sizeof(array); i++) {
array = i;
}
foo(array,
"1 3 5 7 9 11 13 15 17 190 2 4 6 8 10 12 14 16 18",
sizeof(array) / sizeof(array));
}
赚小钱 发表于 2020-5-29 02:00
感谢解答!但是不知道为什么我运行的时候有错误C:\Users\lenovo\Desktop 优秀的Aurora 发表于 2020-5-29 12:36
感谢解答!但是不知道为什么我运行的时候有错误
'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _strdup. See online help for details.
'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
优秀的Aurora 发表于 2020-5-29 12:38
'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant na ...
把你的报错信息扔到 google translate 或者 有道词典。
页:
[1]