Thursday, April 2, 2015

Linux System Programming - File IO

Copy   
 
Program:
 
    1 #include <stdio.h>
    2 #include <stdlib.h>
    3 #include <fcntl.h>
    4 #include <sys/types.h>
    5 #include <sys/stat.h>
    6 
    7 #define BUFSIZE 1024
    8 
    9 void printex(char *str) {
   10     fprintf(stderr, "%s\n", str);
   11     exit(EXIT_FAILURE);
   12 }
   13 
   14 void printerr(char *str) {
   15     perror(str);
   16     exit(EXIT_FAILURE);
   17 }
   18 
   19 int main(int argc, char *argv[]) {
   20     int rdfd, wrfd, nread, nwrite;
   21     char buf[BUFSIZE];
   22 
   23     if (argc != 3) {
   24         printex("Usage: mycopy <file1> <file2>");
   25     }
   26 
   27     rdfd = open(argv[1], O_RDONLY);
   28     if (-1 == rdfd){
   29         printerr("source file open");
   30     }
   31 
   32     wrfd = open(argv[2], O_WRONLY | O_CREAT, 
   33                S_IRWXU | S_IRGRP | S_IROTH);
   34 
   35     if (-1 == wrfd) {
   36         printerr("dest file open");
   37     }
   38 
   39     while ((nread = read(rdfd, buf, sizeof(buf))) > 0) {
   40         if ((nwrite = write(wrfd, buf, nread)) != nread) {
   41             printerr("dest file write");
   42         }
   43     }
   44     if (-1 == nread) {
   45         printerr("src file read");
   46     }
   47 
   48     if (close(rdfd) == -1) {
   49         printerr("close src file");
   50     }
   51     if (close(wrfd) == -1) {
   52         printerr("close dest file");
   53     }
   54 
   55     return EXIT_SUCCESS;
   56 }
   57  
 
Strace Log
========== 
reemuskumar ~/prog/cprog/linsys $ strace ./mycopy data2 data3
execve("./mycopy", ["./mycopy", "data2", "data3"], [/* 21 vars */]) = 0
.....
open("data2", O_RDONLY)                 = 3
open("data3", O_WRONLY|O_CREAT, 0744)   = 4
read(3, "abcdefghijklmnopqrstuvwxyz\nabcde"..., 1024) = 270
write(4, "abcdefghijklmnopqrstuvwxyz\nabcde"..., 270) = 270
read(3, "", 1024)                       = 0
close(3)                                = 0
close(4)                                = 0
exit_group(0)                           = ?
+++ exited with 0 +++
 

Starting from the first

I want to start learning programming again with C++ 11. Programming is always a fascinating art for me and C++ is always been by favorite Programming Language.

Reading orders of the C++ Programming Books:

1.  Programming: Principles and Practice Using C++ - Bjarne Stroustrup


2. C++ Primer - Stanley Lippmann, Josee Lajoie, Barbara E.Moo


3. C++ for the Impatient - Brian Overland


4. The C++ Programming Language - Bjarne Stroustrup

My Goal for this year is to complete reading the first 2 books along with Linux Programming Interface book by Micheal Kerrisk. This seems to be a lofty goal, will try my level best to achieve it.