2022年5月15日 星期日

[C/C++] 讀檔

說明:
讀檔

Code:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

#define BOOL                    int
#define TRUE                    0
#define FALSE                   -1
#define MAX_LONG_LENGTH         1024
#define MAX_SHORT_LENGTH        128

BOOL load_file_fun(char *filename, char **p_content)
{
    int fd = -1;    
    int totalsize = 0;
    int readsize = 0;
    char buffer[MAX_SHORT_LENGTH];
    BOOL ret = FALSE;
    
    if ( (fd = open((char *)filename, O_RDONLY)) > 0 )
    {
        totalsize = 0;
        while( (readsize = read(fd, buffer, MAX_SHORT_LENGTH)) > 0)
            totalsize += readsize;

        if (totalsize <= 0)
        {
            printf("[ERROR] %s file size is wrong!\n", filename);
            return ret;
        }    
        
        if (lseek(fd, 0, SEEK_SET) == -1)
        {
            printf("[ERROR] %s can't seek!\n", filename);
            return ret;
        }
        
        *p_content = (char*)malloc( ( totalsize + 1) * sizeof(char));
        memset(*p_content, '\0', totalsize + 1);

        if (*p_content)
        {
            if(read(fd, *p_content, totalsize) > 0 )
            {
                ret = TRUE;
            }
            else
            {
                printf("[ERROR] %s can't read!\n", filename);
                free(*p_content);
            }

            close(fd);
        }
    }
    else
        printf("[ERROR] Open %s fail!\n", filename);

    return ret;    
}

int main(int argc, char *argv[])
{
    char *p_content = NULL;
    
    if (load_file_fun("/etc/exports", &p_content) == TRUE)
    {
        printf("%s\n", p_content);
        
        if (p_content)
            free(p_content);
    }
    
    return 0;
}

Result:
# /etc/exports: the access control list for filesystems which may be exported
#               to NFS clients.  See exports(5).
#
# Example for NFSv2 and NFSv3:
# /srv/homes       hostname1(rw,sync,no_subtree_check) hostname2(ro,sync,no_subtree_check)
#
# Example for NFSv4:
# /srv/nfs4        gss/krb5i(rw,sync,fsid=0,crossmnt,no_subtree_check)
# /srv/nfs4/homes  gss/krb5i(rw,sync,no_subtree_check)
#
/tftpboot       *(insecure,rw,no_subtree_check,no_root_squash,no_all_squash)
/SOURCE         *(insecure,rw,no_subtree_check,no_root_squash,no_all_squash)

沒有留言:

張貼留言