converting File statements of C++ to C language

Hi,
I have following C++ statements:
1
2
3
    ifstream inFile;
    inFile >> num_rows;
    file_buffer.resize(num_rows);


I have converted them into C:

1
2
3
4
5
     vector<double> file_buffer;
     FILE* inFile;
    inFile = fopen(argv[1], "r");
    fgets(strNum_rows, 20, inFile); 
    num_rows = atoi(strNum_rows);


But I can't understand how to declare file_buffer and how to convert :

 
file_buffer.resize(num_rows);


in 'C' language?

Similarly is the following 'C' language statement is the correct conversion of following C++ statement:
1
2
3
4
5
//C language 
   send_buffer = (double *)malloc(num_rows * sizeof(double);

//C++ 
  send_buffer = new double[num_rows];

Some body please guide me.

Zulfi.
Last edited on
@zak100,
First of all, why exactly are you doing this? If this is anything to do with your recent threads on MPI then there is absolutely no need to change from a C++-style to a C-style way of doing things. Your MPI send and receive calls will be perfectly happy with a send buffer created with new: there is absolutely no point in using malloc. And, although vectors aren't particularly great with MPI, you can actually get straight to their original data buffer with, e.g. file_buffer.data().

So, what are you actually trying to do?

Hi,
I want to be consistent with C language. I did all my work with C so I want to do this transformation but the advantage is that I would get two versions of code and I can test their performance.

Zulfi.
I want to be consistent with C language


Consistency is possibly of limited value. Choose whichever option yields the better solution.
(A foolish consistency.... https://en.wikipedia.org/wiki/Self-Reliance )
Last edited on
vector<double> file_buffer;
is
double *file_buffer;
..blah blah it gets malloced and data put in it and so on..
and resize looks like this:
double *tmp = malloc(however that works);
memcpy(tmp, file_buffer, oldsize*sizeof(double));
free(file_buffer); //whatever C needs here. I am very rusty
file_buffer = tmp; //bam, its resized data intact.

yes, malloc replaces 'new' for C. I don't remember the gory details of the syntax, and you can look it up as well as I can.

or, ideally, you can just make file_buffer extra big to begin with and not fool with resizing it which is inefficient. you can open a file, get its size, and then allocate your buffer after that if it makes more sense ...
Last edited on
Topic archived. No new replies allowed.