c - 我需要重命名文件,但我不明白出了什么问题,文件被加密了,但名称没有改变
问题描述
我需要重命名文件,但是我不明白哪里出了问题,文件被加密了,但是名称没有改变,如何正确使用rename()函数。我需要将文件名更改为“encrypt.yes”
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char new[20];
char old[20];
int rename(const char *old, const char *new);
int ch;
FILE *fps;
printf("Enter file name (with extension like file.txt) to encrypt : ");
strcpy(new,"encrypt.yes");
rename(old, new);
scanf("%s", old);
fps = fopen(old, "r+");
if (fps == NULL) {
printf("Could not open file '%s'\n", old);
return 1;
}
while ((ch = fgetc(fps)) != EOF) {
ch += 100;
fseek(fps, -1, SEEK_CUR);
fputc(ch, fps);
fseek(fps, 0, SEEK_CUR);
}
fclose(fps);
printf("File '%s' encrypted successfully\n", old);
return 0;
}
解决方案
不知道我是否完全理解您,但我认为您正在尝试按原样修改每个字节。将此答案调整为您的代码,您可以执行以下操作。注意:仍有很大的改进空间和错误处理。
Also, I know you tagged this as Windows, but my Windows VM is screwing up at the moment, so I wrote and tested this code on Linux with gcc. It may work on Windows as-is, but I did not test it. Nonetheless, I think it's straight-forward enough to get you 95% there. The key is opening the file in "r+" mode so you can read from and write to it.
And lastly, don't gloss over the comments you've gotten so far from Paul Ogilvie and David C. Rankin; that's good advice.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char fname[20];
int ch;
FILE *fps;
printf("Enter file name (with extension like file.txt) to encrypt : ");
scanf("%s", fname);
fps = fopen(fname, "r+");
if (fps == NULL) {
printf("Could not open file '%s'\n", fname);
return 1;
}
while ((ch = fgetc(fps)) != EOF) {
ch += 100;
fseek(fps, -1, SEEK_CUR);
fputc(ch, fps);
fseek(fps, 0, SEEK_CUR);
}
fclose(fps);
printf("File '%s' encrypted successfully\n", fname);
return 0;
}
推荐阅读
- java - 是否有一个 Spring 函数可以删除 CSV 文件中的引号字符或分隔符?
- javascript - 重新分配不会改变 java 脚本中 const 的值吗?
- oracle - OracleXE 在 Windows 上安装 SCOTT 模式
- python - python中的repr方法是否应该总是返回字符串
- ionic3 - 为 Ionic V3 应用安装 Campaign Tracking
- google-cloud-platform - 启用 GCP cloudresourcemanager gcloud config joe.bloggs@googlemail.com 帐户与 GCP 项目所有者角色 joe.bloggs@gmail.com 不匹配
- javascript - 初始路由器推送(VueJS)后,组件道具没有反应
- javascript - 无法发出 Http 请求
- r - 如何计算距离下一次发生的天数?
- json - 将对象转换为可编码对象失败:“偏移”实例