简体   繁体   中英

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).

In addition, int fclose(FILE*) , takes an open file pointer, not a string, as its argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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