复制文件并向后写入文件信息

标签 c

需要为之前创建的文件创建一个副本,其中包含 15 个随机数,并在此副本中将这些数字倒序写入。

我尝试用 for() 读取文件并写入数组,这也会用 for() 填充新创建的文件,但是 IDE 会在执行 for() 时立即停止脚本。

#include <stdio.h>
#include <stdlib.h>

int main(){
char a[20], sf[20], tf[20];
FILE *source, *target;
int i;

printf("Enter name of file to copy\n");
gets(sf);

source = fopen(sf, "r");

if (source == NULL){
    printf("Press any key to exit...\n");
    exit(1);
}

printf("Enter name of target file\n");
gets(tf);

target = fopen(tf, "w");

if (target == NULL){
    fclose(source);
    printf("Press any key to exit...\n");
    exit(1);
}

for(i=0;i<15;i++){
    fscanf(source, "%d", a[i]);
    //printf("%d\n", a[i]);
}
for(i=15;i>0;i--){
    fprintf(target, "%d\n", a[i]);
}

//printf("File copied successfully.\n");

return 0;
}

最佳答案

一些评论:

  • 如评论中所述,您阅读的是 int,因此您需要一个 int 数组,而不是一个 char 数组来保存它们,目前你将写出具有未定义行为的a

  • 如果你需要保存 15 个值,一个 15 的数组就足够了,20(假设 int)没用

  • 从不使用gets,它已被弃用(多年来)因为危险,使用fgets不要冒险写在接收字符串之外,不要忘记删除可能的换行符

  • 可能是输入文件和输出文件相同,所以在打开输出文件之前先读取并写入其内容

  • fscanf(source, "%d", a[i]); 无效,必须是 fscanf(source, "%d", &a[i]) ;

  • 检查 fscanf 的结果以管理输入文件中的错误情况

  • fprintf(target, "%d\n", a[i]); 必须是 fprintf(target, "%d\n", a[i- 1]);

  • 显式fclose输出文件更好,以防您稍后将程序转换为更复杂的程序


一个建议:

#include <stdio.h>
#include <string.h>

#define N 15

FILE * openIt(const char * msg, const char * dir)
{
  char fn[256];

  printf(msg);

  if (fgets(fn, sizeof(fn), stdin) == NULL)
    /* EOF */
    return NULL;

  char * p = strchr(fn, '\n');

  if (p != NULL)
    *p = 0;

  FILE * fp = fopen(fn, dir);

  if (fp == NULL)
    fprintf(stderr, "cannot open '%s'\n", fn);

  return fp;
}

int main()
{
  FILE * fp;

  if ((fp = openIt("Enter name of file to copy\n", "r")) == NULL)
    return -1;

  int a[N], i;

  for (i = 0; i != N; ++i) {
    if (fscanf(fp, "%d", &a[i]) != 1) {
      fprintf(stderr, "invalid integer rank %d\n", i);
      fclose(fp);
      return -1;
    }
  }

  fclose(fp);

  if ((fp = openIt("Enter name of target file\n", "w")) == NULL)
    return -1;

  while (i--) {
    fprintf(fp, "%d\n", a[i]);
  }

  fclose(fp);

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra r.c
pi@raspberrypi:/tmp $ cat in
1 2 3 4 5
6 7 8 9 10
11 12
13
14
15
not read
pi@raspberrypi:/tmp $ ./a.out
Enter name of file to copy
in
Enter name of target file
out
pi@raspberrypi:/tmp $ cat out
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
pi@raspberrypi:/tmp $ ./a.out
Enter name of file to copy
out
Enter name of target file
out
pi@raspberrypi:/tmp $ cat out
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
pi@raspberrypi:/tmp $ 

关于复制文件并向后写入文件信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55479694/

相关文章:

c - 大约同时处理 2 个信号

c - 不同线程中的多个 epoll_wait 接收不是为它们设计的事件

c - 使用一个 for 循环就地转置矩阵

c - 我在cs50沙箱中混淆了两个程序?

c - fgets 返回更少的字符

c - 二叉搜索树的层序遍历

c - 线程同时运行

我可以通过发送带有 NULL 位图句柄的 STM_SETIMAGE 消息来清除静态控件中的位图吗

c++ - 在 C 中打印 unicode 文字

c - 在不更改代码的情况下使用 gcc 的功能多版本控制是否可行?