0

In a C/C++ program, is it correct for me to do this:

int i;
FILE **files = malloc(numFiles * sizeof(FILE *));
std::string file("foo"), ext(".bar");
char *num[10];

for (i = 0; i < numFiles; i++) {
    files[i] = fopen((file + itoa(i, num, 10) + ext).c_str(), "w");
}

This is basically what I am doing, but I am not getting anything written to the files. They're blank.

EDIT

I have fixed my problem. I thought I might be doing something wrong here, but it turned out to be elsewhere. Thanks for the responses, anyway.

6
  • 7
    Is it C or C++? If you're already using std::string, why not other C++ features instead of, say, raw arrays. Commented Aug 20, 2012 at 15:56
  • 2
    Well, there are no output operations in the code you've shown... Commented Aug 20, 2012 at 15:56
  • 1
    This is an apparently correct, if ugly, C++ (not C or C/C++) fragment. What do you expect it to do? Commented Aug 20, 2012 at 16:05
  • In my experience, C++ is ugly however you write it. I am not a huge fan. Commented Aug 20, 2012 at 16:27
  • 1
    @Luke: It's certainly ugly if you try to blend it with C idioms like that. In my opinion, it can be rather elegant (if occasionally somewhat twisted) if you stick to native idioms. Commented Aug 20, 2012 at 16:30

2 Answers 2

4

Sure they are blanked, you did not write anything, you simply open the file in writing mode!

You have to use the fwrite or fprintf function to write the data to the file and then close the file with fclose.

Sign up to request clarification or add additional context in comments.

8 Comments

or use ofstream and ofstream.operator<<() method.
If you're compiling C++, you need to cast the result of malloc (which is void*). And itoa is a non-standard function. Other than that, code seems ok.
@Luke, the initialization is correct if no error will happen. Do you use fclose function somewhere?
Show a self-contained complete program that demonstrates your problem.
@elyashiv: Performance is one good reason not to use the C++ stream classes. The C equivalents are not as easy to set up and use, but they often work faster. This could be an important consideration, as reading and writing output streams is slow to begin with.
|
2

You have array of pointers to char. But you need array of char. char *num[10]; --> char num[10].

I am wondering how it isn't crashing :)

1 Comment

That was just a typo... it's not like that in the real program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.