简体   繁体   English

C编程。 尝试读写时程序崩溃

[英]C Programming. Program crashing when trying to read and write

I'm having a hard time figuring this problem right now... In one of my functions to copy a file, it always crashes while trying to read from one file to another. 我现在很难解决这个问题...在我复制文件的功能之一中,尝试从一个文件读取到另一个文件时,它总是崩溃。 Also I'm a beginner, so sorry for any mistakes I've done. 另外,我还是个初学者,对于我犯的任何错误,我们深表歉意。

int file_copy(void)
{
    char path_new[MAX_PATH];

    file_load();

    printf("New name: ");
    scanf("%s", path_new);               // <---- Crash right after entering a new path

    FILE *fr_source, *fw_target;

    if (((fr_source = fopen(path_current, "r")) && (fw_target = fopen(path_new, "w"))) == NULL) {
        printf("Error while opening one of these files");
        exit(6);
    }

    int c;

    while((c = getc(fr_source)) != EOF) {
        fputc(c, fw_target);
    }

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

    if ((fclose(path_current)) && (fclose(path_new)) == EOF) {
        printf("Error while closing one of these files");
        exit(7);
    }

    return 0;
}

int file_load(void)
{
   printf("Path to current file: ");
   scanf("%s", path_current);

   if (file_access(path_current) != 0)
       exit(2);

   return 0;
}

int file_access(char path[])
{
    if ((access(path, F_OK)) != 0) {
       printf("ERROR = %s.\n", strerror(errno));
        exit(1);
    }
    return 0;
}

EDIT: Now it works after separating this two: 编辑:现在,将这两个分开后,它可以工作:

if ((fr_source = fopen(path_current, "r")) == NULL) {
    printf("Error while opening one of these files");
    exit(6);
}

if ((fw_target = fopen(path_new, "w")) == NULL) {
    printf("Error while opening '%s'\n", path_new);
    exit(6);
}

Try changing the line 尝试换线

if (((fr_source = fopen(path_current, "r")) && (fw_target = fopen(path_new, "w"))) == NULL) {

to

if (((fr_source = fopen(path_current, "r")) == NULL) || ((fw_target = fopen(path_new, "w")) == NULL)) {

Similarly, 同样的,

if ((fclose(path_current)) && (fclose(path_new)) == EOF) {

should be 应该

if ((fclose(fr_source) == EOF) || (fclose(fw_target) == EOF)) {

Using the format (ptr1 && ptr2) == NULL is confusing, and throws warnings on many compilers (certainly if you use gcc -Wall -pedantic , which I do). 使用格式(ptr1 && ptr2) == NULL会造成混淆,并且会在许多编译器上引发警告(当然,如果您使用gcc -Wall -pedantic ,我会这样做)。

In addition, int fclose(FILE*) , takes an open file pointer, not a string, as its argument. 另外, int fclose(FILE*) ,将打开文件指针而不是字符串作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM