【发布时间】:2017-03-27 00:19:03
【问题描述】:
我正在使用一个打开文件的函数, 将该文件的内容读入动态数组的函数, 关闭文件的函数。
到目前为止,除了当我返回调用位置(主)时动态数组超出范围之外,我能够执行上述所有操作。我想在主函数甚至单独的函数中将其他数据存储在数组中。完成将数据添加到动态数组后,我会将其内容写回源文件,用新数据覆盖它,然后关闭该文件。目的是将数据附加到原始文件的顶部。我在 main 中无法访问或修改函数 char *LoadFileData(FILE *fp, char* charPtr); 做错了什么?
感谢您对此的帮助。
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;
}
【问题讨论】:
-
charPtr = new char;不会为您分配动态数组。请改用new char[length]。 -
您的数组没有超出范围,您没有将其指针返回到您的调用函数。您的 charPtr 参数可以作为 char*& charPtr 传递。或者按照其他人的建议分配返回值。
标签: c++ c function dynamic-arrays file-pointer