を呼び出してからそれを操作し、 。は動的配列、ファイルを閉じ 関数に、そのファイルの内容を読み取り機能を別の関数で動的配列を作成し、私は、ファイルを開く機能を働いている機能
これまでのところ、呼び出し元の場所(メイン)に戻ったときに動的配列が範囲外になることを除いて、私は上記のすべてを行うことができました。私はメインまたは別の機能の中で、配列に追加のデータを保存したい。動的配列にデータを追加したら、その内容をソースファイルに書き込んで新しいデータで上書きし、そのファイルを閉じます。目的は、元のファイルの先頭にデータを追加することです。関数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として渡すことができます。他に提案されているように、戻り値を代入します。 –