ابزار کاربر

ابزار سایت


c-programming:files:start

Accessing Files


Low-level IO with System Calls

// gcc -Wall -Werror -Wextra -pedantic -std=c99  write-to-file.c 
 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
 
int main(void)
{
    char *pathname = "new.txt";
    int flags = O_WRONLY | O_CREAT | O_APPEND;
    mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP;
    int fd = open(pathname, flags, mode);
    if(fd == -1) {
        perror("open() error");
        exit(EXIT_FAILURE);
    }
 
    char buf[] = "This is a line.\n";
    write(fd, buf, sizeof(buf));
 
    close(fd);
 
    return 0;
}
// gcc -Wall -Werror -Wextra -pedantic -std=c99 copy-file.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
 
#define BUFSIZE 32768
 
int main(void)
{
    char buf[BUFSIZE] = {0};
 
    char src_fname[] = "bonding.txt";
    char dst_fname[] = "new.txt";
 
    int srcfd = open(src_fname, O_RDONLY);
    if (srcfd == -1) {
        perror("Cannot open source file");
        exit(EXIT_FAILURE);
    }
 
    int dstfd = open(dst_fname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
    if (dstfd == -1) {
        perror("Cannot open destination file");
        exit(EXIT_FAILURE);
    }
 
    int i;
    ssize_t bytes_read;
    ssize_t bytes_written;
    ssize_t total_read = 0;
    ssize_t total_written = 0;
    for(i = 0; (bytes_read = read(srcfd, buf, sizeof(buf))) > 0; i++) {
 
        bytes_written = write(dstfd, buf, bytes_read);
 
        total_read += bytes_read;
        total_written += bytes_written;
 
        printf("[%d] Read %ld bytes from %s and wrote %ld bytes to %s\n",
                i+1, bytes_read, src_fname, bytes_written, dst_fname);
    }
    printf("\nRead %ld total bytes from %s and wrote %ld total bytes to %s "
           "over %d iterations\n",
           total_read, src_fname, total_written, dst_fname, i);
 
    close(srcfd);
    close(dstfd);
    return 0;
}
c-programming/files/start.txt · آخرین ویرایش: 2024/04/19 17:58 توسط pejman

به جز مواردی که ذکر می‌شود، مابقی محتویات ویکی تحت مجوز زیر می‌باشند: Public Domain
Public Domain Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki