Do I need to malloc when creating a file to write to?
The fil开发者_运维问答e will be based on the contents of 2 others, so would I need to malloc space for the writeable file of sizeof( file a ) + sizeof( file b) + 1
?
Sorry if this makes no sense; if it doesn't then I guess I need to go read some more :D
Essentially, I have 2 txt files and a string sequence - I am writing each line of each file side by side separated by the string sequence.
txt file a
hello stack over
flow this
is a test
txt file b
jump the
gun i am
a novice
seperator == xx
output ==
hello stack overxxjump the
flow thisxxgun i am
is a testxxa novice
If you're writing it in order, can't you just use fprintf()
or fwrite()
whenever you need to write something out, instead of writing the entire file at once?
EDIT: Based on your update, here's basically what you have to do (probably not valid C since I'm not a C programmer):
EDIT2: With some help from msw:
const int BUFSIZE = 200;
FILE *firstFile = fopen("file1.txt", "r");
FILE *secondFile = fopen("file2.txt", "r");
FILE *outputFile = fopen("output.txt", "w");
char* seperator = "xx";
char firstLine[BUFSIZE], secondLine[BUFSIZE];
// start a loop here
fgets(firstLine, 200, firstFile);
fgets(secondLine, 200, secondFile);
// Remove '\n's from each line
fprintf(outputFile, "%s%s%s", firstLine, seperator, secondLine);
// end a loop here
fclose(outputFile);
fclose(firstFile);
fclose(secondFile);
You only need to malloc
the entire size of a file if you need to hold the entire file in memory (and even then, you can probably use mmap
or something instead). Allocate as much memory as you need for the data you intend to work with in memory: no more, no less.
Files are on disk, malloc is for RAM.
You'd only malloc if you needed space in memory to store the data PRIOR to writing out to the file, otherwise, typically you'd use a stack allocated buffer of say 8k to write to the file in chunks.
So taking your question as-is, no you'd rarely malloc just to write to a file.
If your goal is to keep the file in memory in completion, then you'd malloc sizeof file.
精彩评论