Search code examples
c++cfilevectordynamic-arrays

Vector type inside fgets


I have this theory, I can grab the file size using fseek and ftell and build a dynamic array as a buffer. Then use the buffer for fgets(). I currently can not come up with a way to do it.

My theory is based off of not knowing the size of the first file in bytes. So, I do not know how big of a buffer to build. What if the file is over 2 gigs? I want to be able to build a buffer that will change and recognize the file size of whatever file I put into SearchInFile().

Here is what I have so far below:

int SearchInFile(char *fname, char *fname2)
{
    FILE *pFile, *pFile2;
    int szFile, szFile2;

    // Open first file
    if( (fopen_s(&pFile, fname, "r")) != NULL )
    {
        return(-1);
    }

    // Open second file
    if( (fopen_s(&pFile2, fname2, "r")) != NULL )
    {
        return(-1);
    }

    // Find file size 
    fseek(pFile, 0L, SEEK_END);
    szFile = ftell(pFile);
    // Readjust File Pointer
    fseek(pFile, 0L, SEEK_SET);

    std::vector <char> buff;
    //char buff[szFile];

    while(fgets(buff.push_back(), szFile, pFile))
    {


    }

Any thoughts or examples would be great. I've been searching the net for the last few hours.


Solution

  • Vector can grow, so you don't have to know the size beforehand. The following four lines do what you want.

    std::vector<char> buff;
    int ch;
    while ((ch = fgetc(pFile)) != EOF)
        buff.push_back(ch);
    

    fgetc is a function to read a single char, simpler than using fgets.

    If you do know the file size beforehand then you could call buff.reserve(szFile) before the loop. This will make the loop a little more efficient.