我正在使用一个打开文件的函数, 一个将该文件的内容读入动态数组的函数, 一个关闭文件的函数。
到目前为止,我能够完成上述所有操作,但当我回到调用位置(main)时,动态数组超出了范围。我想在main或甚至单独的函数中存储数组中的其他数据。一旦我完成向动态数组添加数据,我会将其内容写回源文件,用新数据覆盖它然后关闭该文件。目的是将数据附加到原始文件的顶部。我无法在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
Ĵ
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;
}
答案 0 :(得分:3)
不是传入你从未使用过的char *
值,而是将函数的返回值赋给tempFileData
。
所以改变这个功能:
char *LoadFileData(FILE *fp)
{
char* charPtr;
...
然后这样称呼:
tempFileData = LoadFileData(fSource);
答案 1 :(得分:3)
其中一个问题是以下几行的组合:
charPtr = new char; // create dynamic array to hold the file contents
charPtr[i++] = ch;
您只为一个char
分配内存,但继续使用它,就像它可以容纳很多字符一样。
你需要:
答案 2 :(得分:2)
如何归还string
?
string LoadFileData(FILE *fp, char* charPtr)
答案 3 :(得分:0)
根据每个人的反馈,这是有效的修改。谢谢!
char* LoadFileData(FILE *fp)
{
off_t size; // Type off_t represents file offset value.
int i = 0;
char ch = '\0';
char *charPtr; // dynamic arrary pointer that will hold the file contents
fseek(fp, 0L, SEEK_END); // seek to the end of the file
size = ftell(fp); // read the file size.
rewind(fp); // set the file pointer back to the beginning
// create a dynamic array to the size of the file
charPtr = new char[size + 1];
if (charPtr == NULL) {
printf("Memory can't be allocated\n");
// exit(0);
}
while (ch != EOF) {
ch = fgetc(fp); // read source file one char at a time
if (ch < 0) { // do not copy it if it is an invalid char
}
else {
charPtr[i++] = ch;
// load the char into the next ellement of the array
// i++;
}// end else
} // end while
return charPtr;
}