Domanda

It may look simple but I'm to find the reason why it's not working. I have two functions read_file_cpp() & write_file_cpp(). read_file_cpp() reads a file and stores it in unsigned char pointer & write_file_cpp() write back data from unsigned char pointer to the file.

But when I use basic_ifstream<unsigned char> or basic_ofstream<unsigned char> file streams, both the functions could not read/write data and contents of unsigned char pointers remains unchanged. Given below are code snippets :

int read_file_cpp(unsigned char *pInData,
                  int in_len,
                  string file_name) {

    basic_ifstream<unsigned char> file_stream;

    file_stream.open(file_name.c_str(),ios::in | ios::binary);

    if (!file_stream.is_open()) {
        cout << stderr << "Can't open input file !\n";
        exit(1);
    }
    else{
        file_stream.read(pInData,in_len);
    }

    file_stream.close();

    return 0;
}

int write_file_cpp(string file_name,
                   unsigned char *pOutData,
                   int out_len) {

basic_ofstream<unsigned char> file_stream;

file_stream.open(file_name.c_str(),ios::out | ios::binary | ios::trunc);

if (!file_stream.is_open()) {
    cout << stderr << "Can't open output file !\n";
    exit(1);
}
else{
    file_stream.write(pOutData,out_len);
}

file_stream.close();

return 0;
}

But when I use ifstream or ofstream and typecast to char pointer, both the functions work properly ,i.e.,

int read_file_cpp(unsigned char *pInData,
                  int in_len,
                  string file_name) {

    ifstream file_stream;

    file_stream.open(file_name.c_str(),ios::in | ios::binary);

    if (!file_stream.is_open()) {
        cout << stderr << "Can't open input file !\n";
        exit(1);
    }
    else{
        file_stream.read((char *)pInData,in_len);
    }

    file_stream.close();

    return 0;
}

is working properly. Is there a way to make basic_ifstream<unsigned char> or basic_ofstream<unsigned char> work properly for unsigned char pointer types or to avoid typecast when ifstream or ofstream is used?

È stato utile?

Soluzione

The typecast is required because there are no istream or ostream methods for unsigned char.

By the way, in your functions you may want to return the actual bytes written or read (otherwise it's redundant since it is passed in.)

Use std::istream::gcount to get the characters read.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top