更正以下代码:#include <stdio.h> #include <fcntl.h> #include <stdlib.h> #define Length 1024 int main( ) { int fdw, fdr, len; char str[Length]; char sourcename[15],targetname[20]; printf("Please input the name of the source file: "); gets(sourcename); printf("Please input the name of the target file: "); gets(targetname); fdr=open(sourcename,O_RDONLY); if (fdr) len=read(fdr,str,Length); else { printf("read file error"); exit(0); } fdw=open(targetname,O_CREAT|O_RDWR); write(fdw,str,len); close(fdr); close(fdw); }
时间: 2024-01-20 17:02:04 浏览: 27
更正后的代码如下:
```c
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#define Length 1024
int main() {
int fdw, fdr, len;
char str[Length];
char sourcename[15], targetname[20];
printf("Please input the name of the source file: ");
scanf("%s", sourcename);
printf("Please input the name of the target file: ");
scanf("%s", targetname);
fdr = open(sourcename, O_RDONLY);
if (fdr < 0) {
printf("Failed to read the source file.");
exit(0);
}
len = read(fdr, str, Length);
fdw = open(targetname, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR);
if (fdw < 0) {
printf("Failed to create the target file.");
exit(0);
}
write(fdw, str, len);
close(fdr);
close(fdw);
return 0;
}
```
修改的内容如下:
1. 使用 `scanf()` 函数代替 `gets()` 函数,避免缓冲区溢出问题。
2. 在打开目标文件时加入了文件权限参数,防止程序产生权限问题。
3. 增加了错误处理机制,包括文件打开失败时的处理和文件创建失败时的处理。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)