The "r" function works well!

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

int main(void){
FILE *file_r, *file_w;
int c;
char fileread[40];
char filewrite[40];

printf("Enter filename to be copied: ");
gets(fileread, 40, stdin);
fileread[strlen(fileread)-1] = '\0';
file_r = fopen(fileread, "r");
while(file_r == NULL)
    {
    printf("Invalid file, ealnter again!");
    fgets(fileread, 40, stdin);
    fileread[strlen(fileread)-1] = '\0';
    printf("%s\n", fileread);
    file_r = fopen(fileread, "r");
    }

    printf("Enter name of file copy");
    fgets(filewrite, 40, stdin);
    fileread[strlen(fileread)-1] = '\0';
    file_w = fopen(filewrite, "w");


while(file_w == NULL)
    {
    printf("Invalid Filename enter again");
    fgets(filewrite, 40, stdin);
    fileread[strlen(fileread)-1] = '\0';
    file_r = fopen(fileread, "w");

    }


    c = getc(file_r);
    while(c != EOF)
        {
        putc( c, file_w);
        c = getc(file_r);
        }
    fclose(file_r);
    fclose(file_w);
    printf("Files succesfully copied");
    return 0; 
}

Recommended Answers

All 2 Replies

Repeated fileread[strlen(fileread)-1] = '\0'; instead of filewrite..ooops

You've cut and pasted parts of the code but neglected to modify everything. For example, in the file_w part of the code you're still working with fileread rather than filewrite. Compare and contrast with this corrected code:

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

int main(void)
{
    FILE *file_r, *file_w;
    int c;
    char fileread[40];
    char filewrite[40];

    printf("Enter filename to be copied: ");
    fgets(fileread, 40, stdin);
    fileread[strlen(fileread)-1] = '\0';
    file_r = fopen(fileread, "r");

    while(file_r == NULL)
    {
        printf("Invalid file, ealnter again!");
        fgets(fileread, 40, stdin);
        fileread[strlen(fileread)-1] = '\0';
        printf("%s\n", fileread);
        file_r = fopen(fileread, "r");
    }

    printf("Enter name of file copy");
    fgets(filewrite, 40, stdin);
    filewrite[strlen(filewrite)-1] = '\0';
    file_w = fopen(filewrite, "w");

    while(file_w == NULL)
    {
        printf("Invalid Filename enter again");
        fgets(filewrite, 40, stdin);
        filewrite[strlen(filewrite)-1] = '\0';
        file_r = fopen(filewrite, "w");
    }

    c = getc(file_r);

    while(c != EOF)
    {
        putc( c, file_w);
        c = getc(file_r);
    }

    fclose(file_r);
    fclose(file_w);
    printf("Files succesfully copied");

    return 0; 
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.