我正在使用一个打开文件的函数,一个将该文件的内容读入动态数组的函数,一个关闭文件的函数。
到目前为止,除了当我回到调用位置(主)时动态数组超出范围之外,我能够完成上述所有操作。我想在主函数甚至单独的函数中将其他数据存储在数组中。完成将数据添加到动态数组后,我会将其内容写回源文件,用新数据覆盖它,然后关闭该文件。目的是将数据附加到原始文件的顶部。我char *LoadFileData(FILE *fp, char* charPtr);
在 main 中无法访问或修改它的功能有什么问题?
感谢您对此的帮助。
FILE *fSource; // create source file pointer instance
char mode[] = "a+"; // default file open mode
char inStr[80]; // string to get input from user
char *tempFileData; // dynamic string to hold the existing text file
// Open the source file
strcpy(mode, "r"); // change the file opnen mode to read
FileOpen(&fSource, mode);
// Load the source file into a dynamic array
LoadFileData(fSource, tempFileData); // this is where I fail that I can tell.
printf("%s", tempFileData); // print the contents of the (array) source file //(for testing right now)
FileClose(&fSource); // close the source file
j
char *LoadFileData(FILE *fp, char* charPtr)
{
int i = 0;
char ch = '\0';
charPtr = new char; // create dynamic array to hold the file contents
if(charPtr == NULL)
{
printf("Memory can't be allocated\n");
exit(0);
}
// loop to read the file contents into the array
while(ch != EOF)
{
ch = fgetc(fp); // read source file one char at a time
charPtr[i++] = ch;
}
printf("%s", charPtr); // so far so good.
return charPtr;
}