프로그래밍 노트

파일 행수 취득 하는 소스 본문

Win32 SDK 초보

파일 행수 취득 하는 소스

띠리 2008. 3. 18. 13:09
소스1

int n = 0;

HANDLE hFile = CreateFile(sPath,
    GENERIC_READ,
    FILE_SHARE_READ,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

if(hFile == INVALID_HANDLE_VALUE)
// 에러
else
{
    char buffer[65536];
    DWORD dwRead;
    int n = 0;
    while(1)
    {
        if(!ReadFile(hFile, buffer, sizeof buffer, &dwRead, NULL) || !dwRead)
            break;
        n += std::count(buffer, buffer + dwRead, '\n');
    }
    CloseHandle(hFile);
}



소스2

static int count_ln_by_buffer (const char *filename)
{
    HANDLE hFile;
    char *start, *p;
    DWORD len, line_num = 0;
    DWORD dwRead;

    hFile = CreateFile (
        filename,
        GENERIC_READ,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if (!hFile)
        return -1;

    len = GetFileSize (hFile, NULL);

    start = p = malloc (len);
    ReadFile (hFile, start, len, &dwRead, NULL);

    for (; (DWORD) (p - start) < len; p++)
    {
        if (*p == '\n')
        line_num++;
    }

    CloseHandle (hFile);

    return line_num;
}

static int count_ln_by_file_mapping (const char *filename)
{
    HANDLE hFile, hMap;
    const char *start, *p;
    DWORD len, line_num = 0;

    hFile = CreateFile (
        filename,
        GENERIC_READ,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if (!hFile)
        return -1;

    hMap = CreateFileMapping (
        hFile,                     /* Current file handle */
        NULL,                    /* Default security */
        PAGE_READONLY,  /* Read/write permission */
        0,                          /* Max. object size. */
        0,                          /* Size of hFile */
        NULL);                   /* Name of mapping object */

    if (!hMap)
        return -1;

    start = p = MapViewOfFile (
        hMap,                    /* Handle to mapping object */
        FILE_MAP_READ,    /* Read/write permission */
        0,                          /* Max. object size. */
        0,                          /* Size of hFile */
        0);                        /* Map entire file */

    if (!p)
        return -1;

    len = GetFileSize (hFile, NULL);

    for (; (DWORD) (p - start) < len; p++)
    {
        if (*p == '\n')
            line_num++;
    }

    CloseHandle (hMap);
    CloseHandle (hFile);

    return line_num;
}

int main (int argc, char *argv[])
{
    if (argc <= 1)
        return -1;

    return count_ln_by_buffer (argv[1]);
}


Comments