Clarification with C-style Strings
I've managed to load all of the text from a file into a single string. But I'm not sure if the way I've handled it is very safe, or very memory efficient. I'm still learning how all this stuff works.
Code:
...
while((nextChar = fgetc(file)) != EOF)
{
fileData = strConcat(fileData, (char *)&nextChar);
}
...
char *strConcat(char *str1, char *str2)
{
size_t size = strlen(str1) + strlen(str2) + 1;
char *newStr = (char *)malloc(size);
sprintf_s(newStr, size, "%s%s", str1, str2);
return newStr;
}
I'm mostly worried about my use of malloc. But everything seemed to be working ok so I moved on and then I attempted to write some code to search through this char array for specific characters.
Code:
for (i = 0; i < strlen(fileData); i++)
{
if (*(fileData + i) == '\n')
printf("New line at: %i\n", i);
}
And this seemed to have worked correctly. What I want to do now is assign a char pointer to the start character of each new line. But I can't seem to figure out how to do it. I'll need a dynamically sized array but I can't work out how to make one.