0

我正在使用一个打开文件的函数,一个将该文件的内容读入动态数组的函数,一个关闭文件的函数。

到目前为止,除了当我回到调用位置(主)时动态数组超出范围之外,我能够完成上述所有操作。我想在主函数甚至单独的函数中将其他数据存储在数组中。完成将数据添加到动态数组后,我会将其内容写回源文件,用新数据覆盖它,然后关闭该文件。目的是将数据附加到原始文件的顶部。我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;
  }
4

4 回答 4

3

不要传入char *你从不使用的值,而是将函数的返回值分配给tempFileData.

所以改变这样的功能:

char *LoadFileData(FILE *fp)
{
    char* charPtr;
    ...

然后像这样调用它:

tempFileData = LoadFileData(fSource);  
于 2017-03-27T00:28:15.437 回答
3

问题之一是以下几行的组合:

charPtr = new char; // create dynamic array to hold the file contents

    charPtr[i++] = ch;

您只为一个分配内存,char但继续使用它,就好像它可以容纳很多字符一样。

你需要:

  1. 查找文件中存在的字符数。
  2. 为所有字符分配内存(如果需要空终止数组,则为 +1)。
  3. 读取文件内容到分配的内存。
于 2017-03-27T00:28:22.927 回答
2

退货怎么样string

string LoadFileData(FILE *fp, char* charPtr)
于 2017-03-27T00:27:02.617 回答
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; 
} 
于 2017-03-27T20:51:39.897 回答