eral
eral

Reputation: 123

segmentation fault while copying a file

I have below simple code , but when I compile and run with GCC on unix, I got segmentation error. Is it because file naming or copying one file to others. Any help appreciated..

#include <iostream>
#include <stdio.h>

using namespace std;

void copy(char *infile, char *outfile) {
    FILE *ifp; /* file pointer for the input file */
    FILE *ofp; /* file pointer for the output file */
    int c; /* character read */
    /* open i n f i l e for reading */
    ifp = fopen (infile , "r" );
    /* open out f i l e for writing */
    ofp = fopen(outfile, "w");
    /* copy */
    while ( (c = fgetc(ifp)) != EOF) /* read a character */
        fputc (c, ofp); /* write a character */
    /* close the files */
    fclose(ifp);
    fclose(ofp);
}

main() 
{
copy("A.txt","B.txt");
}

Upvotes: 0

Views: 593

Answers (3)

user1502952
user1502952

Reputation: 1420

Use copy(const char* infile, const char* outfile) in arguments to avoid unnecessary warnings.

Also your files may not be in the current directory in which you are executing code. So give complete path to your file.

Upvotes: 0

John Jesus
John Jesus

Reputation: 2404

IF A.txt does not exist, the value of ifp will be NULL (0). Then, this function call will segfault.

fgetc(ifp)

So, change your code to check for NULL on the file opens (each file), for example:

ifp = fopen (infile , "r" );
if (ifp == NULL) {
    printf("Could not open %s\n", infile);
    exit(-2);
}

You may have to add this include also at the top of your file:

#include <stdlib.h>

Upvotes: 1

Gangadhar
Gangadhar

Reputation: 10516

The code which you have posted is correct

 ifp = fopen (infile , "r" );  //will return NULL if file not there 

 while ( (c = fgetc(ifp)) != EOF)     

The moment you are using , Here is a possibility if you do not have A.txt file in your current directory then you will get segmentation fault.

Upvotes: 1

Related Questions