2022年5月15日 星期日

[C/C++] 存檔

說明:
存檔

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

#define BOOL                    int
#define TRUE                    0
#define FALSE                   -1
       
BOOL save_file_fun(char *filename, char *buffer)
{
    int        fd = 0;
    int     length = 0;
    BOOL    ret = FALSE;

    length = strlen(buffer);
    
    if ( (fd = open( filename,
            O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) > 0 )
    {
        if ( write(fd, buffer, length) == length )
            ret = TRUE;
        else
            printf("[ERROR] write %s failed!\n", filename);

        if (fd) 
            close(fd);
        
        sync();
    }
    else
        printf("[ERROR] cannot creat %s!\n", filename);

    return ret;
}       

int main(int argc, char *argv[])
{
    char save[] = "abcde\n12345\n";
    save_file_fun("./save.txt", save);
    
    return 0;
}

Result:
會看見save.txt檔案

沒有留言:

張貼留言