Skip to main content

C - Ritchie & Kernighan - Part 3

Chapter 7-Input and Output

 

  1. 'prog <infile' causes prog to read characters from infile instead. 'otherprog | prog' runs the two programs otherprog and prog, and pipes the standard output of otherprog into the standard input for prog. 'prog >outfile' will write the standard output to outfile instead of stdout. These can be used when using getchar & putchar
  2. Each conversion specification begins with a % and ends with a conversion character. Between the % and the conversion character there may be, in order:
  • A minus sign, which specifies left adjustment of the converted argument.
  • A number that specifies the minimum field width. The converted argument will be printed in a field at least this wide. If necessary it will be padded on the left (or right, if left adjustment is called for) to make up the field width.
  • A period, which separates the field width from the precision.
  • A number, the precision, that specifies the maximum number of characters to be printed from a string, or the number of digits after the decimal point of a floating-point value, or the minimum number of digits for an integer.
  • An h if the integer is to be printed as a short, or l (letter ell) if as a long.
  1. The following are the conversion characters in c
    Character
    Argument type; Printed As
    d,i
    int; decimal number
    o
    int; unsigned octal number (without a leading zero)
    x,X
    int; unsigned hexadecimal number (without a leading 0x or 0X), using abcdef or ABCDEF for 10, ...,15.
    u
    int; unsigned decimal number
    c
    int; single character
    s
    char *; print characters from the string until a '\0' or the number of characters given by the precision
    f
    double; [-]m.dddddd, where the number of d's is given by the precision (default 6).
    E,e
    double; [-]m.dddddde+/-xx or [-]m.ddddddE+/-xx, where the number of d's is given by the precision (default 6).
    G,g
    double; use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f. Trailing zeros and a trailing decimal point are not printed
    p
    void *; pointer (implementation-dependent representation).
    %
    no argument is converted; print a %

    1. A width or precision may be specified as *, in which case the value is computed by converting the next argument (which must be an int)
    2. printf uses its first argument to decide how many arguments follow and what their type is.
    3. The declaration ... means that the number and types of these arguments may vary. The declaration ... can only appear at the end of an argument list.EG:void minprintf(char *fmt, ...)
    4. The type va_list (defined in va_arg)is used to declare a variable that will refer to each argument in turn; this variable is called ap, for ``argument pointer.'' The macro va_start initializes ap to point to the first unnamed argument. It must be called once before ap is used. There must be at least one named argument; the final named argument is used by va_start(ap,last_named_arg) to get started.
    5. Each call of va_arg returns one argument and steps ap to the next; va_arg uses a type name to determine what type to return and how big a step to take. Finally, va_end does whatever cleanup is necessary. It must be called before the program returns.
    6. va_arg(ap, int|float|char*|double) returns an object of that type.
    7. scanf stops when it exhausts its format string, or when some input fails to match the control specification. It returns as its value the number of successfully matched and assigned input items.
    8. The format string in scanf usually contains conversion specifications, which are used to control conversion of input. The format string may contain:
    • Blanks or tabs, which are not ignored.
    • Ordinary characters (not %), which are expected to match the next non-white space character of the input stream.
    • Conversion specifications, consisting of the character %, an optional assignment suppression character *, an optional number specifying a maximum field width, an optional h, l or L indicating the width of the target, and a conversion character.
    1. If assignment suppression is indicated by the * character, however, the input field is skipped; no assignment is made
    2. White space characters are blank, tab, newline, carriage return, vertical tab, and formfeed.
    3. The conversion characters d, i, o, u, and x may be preceded by h to indicate that a pointer to short rather than int appears in the argument list, or by l (letter ell) to indicate that a pointer to long appears in the argument list.
    4. scanf ignores blanks and tabs in its format string. Furthermore, it skips over white space (blanks, tabs, newlines, etc.) as it looks for input values.
    5. Calls to scanf can be mixed with calls to other input functions. The next call to any input function will begin by reading the first character not read by scanf
    6. fclose is called automatically for each open file when a program terminates normally. (You can close stdin and stdout if they are not needed. They can also be reassigned by the library function freopen.)
    7. Output written on stderr normally appears on the screen even if the standard output is redirected.
    8. exit() calls fclose for each open output file, to flush out any buffered output.
    9. The function feof(FILE *) is analogous to ferror; it returns non-zero if end of file has occurred on the specified file.
    10. The function ferror returns non-zero if an error occurred on the stream fp.
    1. char *fgets(char *line, int maxline, FILE *fp)-reads the next input line (including the newline) from file fp into the character array line; at most maxline-1 characters will be read. The resulting line is terminated with '\0'.
    2. int fputs(char *line, FILE *fp)-writes a string (which need not contain a newline) to a file and returns EOF if an error occurs, and non-negative otherwise.

    Chapter 8-UNIX System Calls

     

    1. The system call creat is provided to create new files, or to re-write old ones.int creat(char *name, int perms);
    2. int open(char *name, int flags, int perms); returns a file descriptor, which is just an int. open returns -1 if any error occurs.
    1. In the UNIX operating system, all input and output is done by reading or writing files, because all peripheral devices, even keyboard and screen, are files in the file system. This means that a single homogeneous interface handles all communication between a program and peripheral devices.
    2. int n_read = read(int fd, char *buf, int n);
    int n_written = write(int fd, char *buf, int n); Handle all low level i/o in Unix. Library Functions call these system calls in their implementation.
    1. The standard library function vprintf is like printf except that the variable argument list is replaced by a single argument that has been initialized by calling the va_start macro. Similarly for vfprintf().eg: vprintf(stderr,fmt,arg_list) prints the argument passed where arg_list is intialised using va_list and va_start
    2. The function close(int fd) breaks the connection between a file descriptor and an open file, and frees the file descriptor for use with some other file
    3. The system call lseek provides a way to move around in a file without reading or writing any data:long lseek(int fd, long offset, int origin);sets the current position in the file whose descriptor is fd to offset, which is taken relative to the location specified by origin.

    Miscellaenous

     

    1. far pointer is always a 32 bit pointer storing both segment address and offset. Huge pointer is also 32 bit pointer.Near pointer is 16-bit and restricted to current 64 kb segment in CS or DS
    2. far and Huge ponters are however used to address memory oputised the current 64kb unit..
    3. When K & R (int fun(a) int a)and Ansi(int fun(int a)) ways of function prototype is mixed, error is reported.
    4. When automatic structures are partially intialised, the rest of the elements are set to zero. (char arrays are set to “”)
    5. if(a,b,c) will evaluate to if(c); int x=a,b,c will set x to a
    6. Giving the pattern %*d in printf will cause the compiler to ignore the pattern altogether and continue printing the output, matching the variables with the remaining patterns
    7. In a 'cond?assgn1:assgn2' usage , enclose assgn2 with ().
    8. 'break' should be used only within switch or loop. 'Continue' should be used only within loop
    9. the value of an object can change only once between two seq points.sequence point can be functio call ,semicolon , &&,||. (i++ * i++ is not accepted.)
    10. in ++i*++i , i is incremented twice and then multiplied.(++ has higher precendence than *)
    11. example
    flaot a = 0.7;
    if(a==0.7)
    {
    printf(“hi”);
    }
    this condition is not true since the constant used in the if statement is considered to be a double by default.however representing .7 as .7f would evaluate it to true. .7l will reat it as long double
    1. Printing a variable of different type with unmatching modifier, will yield garbage results. (eg:printing double with %f)
    2. (int)(float_const + 0.5) rounds it off
    3. To suppress the 'floating point not linked error', caused due to failure of the compiler to detect the need for a floating point emulator, can be overcome using this snippet included in the source
    void LinkFloat(void){
    float a=0,*b=&s;a=*b;}
    1. %lf-double %Lf-long double; floating point numbers are stored with <sign><Mantissa><Exp>
    2. Return statement cannot be used as a part of the ternary operator.cond?return(val1):return(val2) is wrong. return(cond?val1:val2) is the correct usage
    3. The pattern #arg will be substituted as “arg” in the macro substitution
    4. The statement printf(“%[-][n.d]s”,str) will print the first ‘d’ characters of the string pointed to by str, right aligned in a field of ‘n’ width.’-‘ option can be used to left align the string.
    5. Scanf(“%[regex]”,..) will match all the text that correspond to the regex. Example: %[^\n]s reads in all characters except ‘\n’
    6. assert(cond_exp) prints an error message if the cond_exp evaluates to zero and the program terminates.

Comments

Popular posts from this blog

Learning Spark Streaming #1

I have been doing a lot of Spark in the past few months, and of late, have taken a keen interest in Spark Streaming . In a series of posts, I intend to cover a lot of details about Spark streaming and even other stream processing systems in general, either presenting technical arguments/critiques, with any micro benchmarks as needed. Some high level description of Spark Streaming (as of 1.4),  most of which you can find in the programming guide .  At a high level, Spark streaming is simply a spark job run on very small increments of input data (i.e micro batch), every 't' seconds, where t can be as low as 1 second. As with any stream processing system, there are three big aspects to the framework itself. Ingesting the data streams : This is accomplished via DStreams, which you can think of effectively as a thin wrapper around an input source such as Kafka/HDFS which knows how to read the next N entries from the input. The receiver based approach is a little compl

Setting up Hadoop/YARN/Spark/Hive on Mac OSX El Capitan

If you are like me, who loves to have everything you are developing against working locally in a mini-integration environment, read on Here, we attempt to get some pretty heavy-weight stuff working locally on your mac, namely Hadoop (Hadoop2/HDFS) YARN (So you can submit MR jobs) Spark (We will illustrate with Spark Shell, but should work on YARN mode as well) Hive (So we can create some tables and play with it)  We will use the latest stable Cloudera distribution, and work off the jars. Most of the methodology is borrowed from here , we just link the four pieces together nicely in this blog.  Download Stuff First off all, make sure you have Java 7/8 installed, with JAVA_HOME variable setup to point to the correct location. You have to download the CDH tarballs for Hadoop, Zookeeper, Hive from the tarball page (CDH 5.4.x page ) and untar them under a folder (refered to as CDH_HOME going forward) as hadoop, zookeeper $ ls $HOME /bin/cdh/5.4.7 hadoop

Enabling SSL in MAMP

Open /Applications/MAMP/conf/apache/httpd.conf, Add the line LoadModule ssl_module modules/mod_ssl.so          or uncomment this out if already in the conf file Also add lines to listen on 80, if not there already Listen 80   ServerName localhost:80 Open /Applications/MAMP/conf/apache/ssl.conf. Remove all lines as well as . Find the line defining SSLCertificateFile and SSLCertificateKeyFile, set it to SSLCertificateFile /Applications/MAMP/conf/apache/ssl/server.crt SSLCertificateKeyFile /Applications/MAMP/conf/apache/ssl/server.key Create a new folder /Applications/MAMP/conf/apache/ssl. Drop into the terminal and navigate to the new folder cd /Applications/MAMP/conf/apache/ssl Create a private key, giving a password openssl genrsa -des3 -out server.key 1024 Remove the password cp server.key server-pw.key openssl rsa -in server-pw.key -out server.key Create a certificate signing request, pressing return for defa