请问C语言怎么实现不损坏两个文件本身的前提之下,的两个文件的内容的交换,是同时交换而不是分别的交换。交换以后的文件要求可以执行,怎么操作代码的实现
这貌似前几天回答过,用内存来做:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file1 = fopen("文件1", "r+");
FILE *file2 = fopen("文件2", "r+");
fseek(file1, 0, SEEK_END);
fseek(file2, 0, SEEK_END);
long int size1 = ftell(file1);
long int size2 = ftell(file2);
rewind(file1);
rewind(file2);
char *content1 = malloc(size1);
char *content2 = malloc(size2);
fread(content1, 1, size1, file1);
fread(content2, 1, size2, file2);
//change
char *temp = content1;
content1 = content2;
content2 = temp;
//rewrite
fwrite(content1, 1, size1, file2);
fwrite(content2, 1, size2, file1);
fclose(file1);
fclose(file2);
free(content1);
free(content2);
return 0;
}
好像又遇到了你 ...
你的题目和你下面的说明,让人有点困惑。比如又A,B两个文件,假设A的内容 111,B的内容是222,根据题目的要求,似乎是A的内容改成222,B的内容改成111.但你的说明中又要求同时交互,不是分别交换,不大理解这个意思。
如此简单。。。将A 和 B 的文件名互换即可
实现两个文件的内容交换,可以按照以下步骤进行:
以下是一个基本的实现示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUF_SIZE 1024
int main(int argc, char* argv[]) {
if (argc != 3) {
printf("Usage: %s file1 file2\n", argv[0]);
return -1;
}
char* file1 = argv[1];
char* file2 = argv[2];
// 打开文件
FILE* fp1 = fopen(file1, "rb");
if (fp1 == NULL) {
printf("Failed to open file %s\n", file1);
return -1;
}
FILE* fp2 = fopen(file2, "rb");
if (fp2 == NULL) {
printf("Failed to open file %s\n", file2);
return -1;
}
// 获取文件大小
fseek(fp1, 0L, SEEK_END);
long size1 = ftell(fp1);
fseek(fp1, 0L, SEEK_SET);
fseek(fp2, 0L, SEEK_END);
long size2 = ftell(fp2);
fseek(fp2, 0L, SEEK_SET);
// 分配内存
char* buf1 = (char*)malloc(size1);
char* buf2 = (char*)malloc(size2);
if (buf1 == NULL || buf2 == NULL) {
printf("Failed to allocate memory\n");
return -1;
}
// 读取文件内容到内存中
fread(buf1, 1, size1, fp1);
fread(buf2, 1, size2, fp2);
// 交换两个文件的内容
char* temp = (char*)malloc(size1);
memcpy(temp, buf1, size1);
memcpy(buf1, buf2, size2);
memcpy(buf2, temp, size1);
free(temp);
// 将交换后的内容写回到文件中
fseek(fp1, 0L, SEEK_SET);
fwrite(buf1, 1, size1, fp1);
fseek(fp2, 0L, SEEK_SET);
fwrite(buf2, 1, size2, fp2);
// 关闭文件和释放内存
fclose(fp1);
fclose(fp2);
free(buf1);
free(buf2);
printf("File content has been swapped successfully.\n");
return 0;
}
在上面的示例中,我们首先打开两个文件并读取它们的内容到内存中,然后使用 memcpy()
函数交换两个文件的内容。最后,将交换后的内容写回到文件中,并关闭文件和释放内存。注意,此示例中没有进行错误处理和异常情况处理,请根据实际情况进行修改和完善。