Fwrite doesn't seem to copy the whole file (just the beginning)

I am trying to make an exe program that can read any file in binary format and later use this binary to make the same file.

So, I realized that I can use fopen(content,"rb")to read the file as binary, and using fwrite, I can write a data block to the stream. But the problem is that when I fwritedo not seem to copy everything.

For example, the text that I opened contains in it 31231232131. When I write it to another file, it only copies 3123(first 4 bytes).

I see that this is a very simple thing that I am missing, but I do not know what.

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

using namespace std;
typedef unsigned char BYTE;
long getFileSize(FILE *file)
{
    long lCurPos, lEndPos;
    lCurPos = ftell(file);
    fseek(file, 0, 2);
    lEndPos = ftell(file);
    fseek(file, lCurPos, 0);
    return lEndPos;
}

int main()
{
    //const char *filePath = "C:\\Documents and Settings\\Digital10\\MyDocuments\\Downloads\\123123.txt";
    const char *filePath = "C:\\Program Files\\NPKI\\yessign\\User\\008104920100809181000405,OU=HNB,OU=personal4IB,O=yessign,C=kr\\SignCert.der";


    BYTE *fileBuf;          
    FILE *file = NULL;      
    if ((file = fopen(filePath, "rb")) == NULL)
        cout << "Could not open specified file" << endl;
    else
        cout << "File opened successfully" << endl;
        long fileSize = getFileSize(file);
        fileBuf = new BYTE[fileSize];
        fread(fileBuf, fileSize, 1, file);
        FILE* fi = fopen("C:\\Documents and Settings\\Digital10\\My Documents\\Downloads\\gcc.txt","wb");
    fwrite(fileBuf,sizeof(fileBuf),1,fi);


    cin.get();
    delete[]fileBuf;
    fclose(file);
    fclose(fi);
    return 0;
}
+4
source share
4
fwrite(fileBuf,fileSize,1,fi);

fileSize , sizeof(...) , , new.

+3

++ :

#include <fstream>

int main()
{
    std::ifstream in("Source.txt");
    std::ofstream out("Destination.txt");
    out << in.rdbuf();
}
+2

fread fwrite. . :

fread(fileBuf, 1, fileSize, file);

fwrite(fileBuf, 1, fileSize, fi);

:

else { }. ++. , .

EDIT: - sizeof(fileBuf) , . , . , sizeof(fileBuf) fileSize, .

0
        fileBuf = new BYTE[fileSize];
        fread(fileBuf, fileSize, 1, file);
        FILE * fi = fopen ("C: \\ Documents and Settings \\ [...] \ gcc.txt", "wb");
    fwrite (fileBuf, sizeof (fileBuf), 1, fi);

fileBufis a pointer to BYTE. You yourself is announced, look: BYTE *fileBuf. And so sizeof(filebuf)there is sizeof(BYTE *).

Perhaps you would like to:

fwrite(fileBuf, fileSize, 1, fi);

which closely reflects the previous challenge fread.

I highly recommend you commit the return values ​​of the I / O functions and check them.

0
source

All Articles