Presentation is loading. Please wait.

Presentation is loading. Please wait.

Files in C Rohit Khokher.

Similar presentations

Presentation on theme: "Files in C Rohit Khokher."— Presentation transcript:

1 Files in C Rohit Khokher

2 Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two major problems It becomes cumbersome and time consuming to handle large volumes of data through terminals. The entire data is lost when either the program is terminated or computer is turned off therefore it is necessary to have more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. This method employs the concept of files to store data.

3 File management in C File management in C,
File operation functions in C, Defining and opening a file, Closing a file, The getw and putw functions, The fprintf & fscanf functions, Random access to files and fseek function.

4 File operation functions in C:
Function Name Operation fopen() Creates a new file for use Opens a new existing file for use fclose Closes a file which has been opened for use getc() Reads a character from a file putc() Writes a character to a file fprintf() Writes a set of data values to a file fscanf() Reads a set of data values from a file getw() Reads a integer from a file putw() Writes an integer to the file fseek() Sets the position to a desired point in the file ftell() Gives the current position in the file rewind() Sets the position to the begining of the file

5 Defining and opening a file
FILE *fp; fp=fopen(“filename”,”mode”); The variable fp is a pointer to the data type FILE. The File is a structure that is defined in the I/O Library. “filename” the file named filename and assigns an identifier to the FILE type pointer fp. The mode defines the purpose R open the file for read only. W open the file for writing only. A open the file for appending data to it.

6 Defining and opening a file
FILE *p1, *p2; p1=fopen(“data”,”r”); p2=fopen(“results”,”w”); In these statements the p1 and p2 are created and assigned to open the files data and results respectively the file data is opened for reading and result is opened for writing. In case the results file already exists, its contents are deleted and the files are opened as a new file. If data file does not exist error will occur.

7 Engineering H192 Winter 2005 Files in C In C, each file is simply a sequential stream of bytes. C imposes no structure on a file. A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a stream is associated with the file. Successfully opening a file returns a pointer to (i.e., the address of) a file structure, which contains a file descriptor and a file control block. Instructor: Much like the keyboard and screen, file input and output is completed via streams. The difference is the computer system typically contains many files, so the programmer must tell the computer which file to connect the stream to. Narrator: Much like the keyboard and screen, file input and output is completed via streams. The difference is the computer system typically contains many files, so the programmer must tell the computer which file to connect the stream to by opening the file. Once a file is open, a pointer to the address of that file structure is established. This file structure contains a file descriptor and file control block. Lecture 07

8 Files in C The statement: FILE *fptr1, *fptr2 ;
Engineering H192 Winter 2005 Files in C The statement: FILE *fptr1, *fptr2 ; declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream. Whenever you are to read from or write to the file, you must first open the file and assign the address of its file descriptor (or structure) to the file pointer variable. Instructor: The FILE declaration is included in the same place as int, float, and char declarations. Since FILE variables are pointers the must be preceded by a * so that the computer knows that the variable will actually contain an address (which will later point to the location of the file itself). Declaring the variables themselves does not connect a file to them. Narrator: File pointers, like any other variable, must be declared. The statement shown declares two file pointers. They can now be assigned the address of a file descriptor, or the location in memory that will be associated with the input or output file stream. Whenever you read from or write to a file, you must first open the file and assign the address of its file descriptor to a file pointer variable. The FILE declaration is included in the same area of your program as int, float or char variable declarations. Notice these FILE pointer variables are preceded by a * so that the computer knows that the variable will contain an address. Declaring the variables themselves does not associate a file descriptor with them. Lecture 07

9 Opening Files The statement: fptr1 = fopen ( "mydata", "r" ) ;
Engineering H192 Winter 2005 Opening Files The statement: fptr1 = fopen ( "mydata", "r" ) ;  would open the file mydata for input (reading). fptr2 = fopen ("results", "w" ) ;  would open the file results for output (writing). Once the files are open, they stay open until you close them or end the program (which will close all files.) Instructor: Simply put, the fopen command connects the given file and creates either an input or output stream to the file. The file pointer that can then be used as a stream is on the left hand side of the = sign. Narrator: Now that file pointers are declared, a file descriptor can now be assigned by opening a file. This is completed by using the fopen() command. Notice in the commands shown the file pointer is on the left hand side of the assignment and the command fopen() opens a given file by its name. The second argument of fopen() determines how to open the file, in this case either for reading or writing. Once these files have been opened, they stay open until you close them, or when your program terminates, which will automatically close all files. Lecture 07

10 Testing for Successful Open
Engineering H192 Winter 2005 Testing for Successful Open If the file was not able to be opened, then the value returned by the fopen routine is NULL. For example, let's assume that the file mydata does not exist. Then: FILE *fptr1 ; fptr1 = fopen ( "mydata", "r") ; if (fptr1 == NULL) { printf ("File 'mydata' did not open.\n") ; } Instructor: A good way to check for fault tolerance is to check for the file pointer to be equal to NULL after attempting to open it. If the file pointer is NULL the program should perform some alternate action besides attempting to use the file pointer (such as displaying an for the user). Narrator: Just because you attempt to open a file doesn’t guarantee it will be opened successfully. Various problems may occur such as the file is in use, your program doesn’t have permission to open the file, or the file simply doesn’t exist or is in another directory. But there is a method of testing for a successful file open. In the given example we will attempt to open a file that doesn’t exist. Notice after we attempt to open the file with fopen we then test the file pointer for a value called NULL. If the file pointer contains NULL then the file in fact didn’t open. Otherwise it can be assumed the file opened correctly and is ready for use. Lecture 07

11 Reading From Files In the following segment of C language code:
Engineering H192 Winter 2005 Reading From Files In the following segment of C language code: int a, b ; FILE *fptr1, *fptr2 ; fptr1 = fopen ( "mydata", "r" ) ; fscanf ( fptr1, "%d%d", &a, &b) ; the fscanf function would read values from the file "pointed" to by fptr1 and assign those values to a and b. Instructor: In the line: fscanf(fptr1,”%d%d”,&a,&b); operates much like the scanf function except it requires the name of the file pointer it should acquire data from. fscanf – the function called Fptr1 – the file pointer fscanf will acquire data from “%d%d” – the expected format of the data in the file (2 integers in this case) &a,&b – the variables where data from the file will be stored Narrator: Once a file is open for reading, there must be a method of reading from the file. The is completed with the fscanf function. It operates much like the scanf function, except this function requires the file pointer to be included as an argument. In the segment of code shown the file mydata is opened and the file pointer fptr1 is assigned to the open file. Then the fscanf function scans for two integers from this file and assigns the values read to the variables a and b. Lecture 07

12 Engineering H192 Winter 2005 End of File The end-of-file indicator informs the program when there are no more data (no more bytes) to be processed. There are a number of ways to test for the end-of-file condition. One is to use the feof function which returns a true or false condition: fscanf (fptr1, "%d", &var) ; if ( feof (fptr1) ) { printf ("End-of-file encountered.\n”); } Instructor: Or to complete a section of code while not at the end of a file: Fscanf(…); While(!feof(fptr1)) { //do something with file data fscanf(…); } Narrator: When reading continuously from a file, eventually the program will reach the end of a file. To determine when this occurs another indicator like the NULL indicator is used, called the end-of-file indictor, or EOF. The pointer will return this indicator when no more data is available to be processed. There are multiple ways to test for the end-of-file condition. A simple method is to use the feof function, which will return a true or false condition. Its use is shown in the example in an if statement. Feof() requires the file pointer being tested as an argument. Lecture 07

13 Engineering H192 Winter 2005 End of File There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanf function: int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == EOF ) { printf ("End-of-file encountered.\n”) ; } Narrator: Another way to test for EOF, much like when testing for NULL, is to check the value returned from fscanf for the EOF indicator. Note that when this method is used you must explicitly assign the output of fscanf to a variable where normally the output of fscanf is ignored. Look closely at the fscanf line on this slide and the preceding slide for this subtle difference. Lecture 07

14 Engineering H192 Winter 2005 Writing To Files Likewise in a similar way, in the following segment of C language code: int a = 5, b = 20 ; FILE *fptr2 ; fptr2 = fopen ( "results", "w" ) ; fprintf ( fptr2, "%d %d\n", a, b ) ; the fprintf functions would write the values stored in a and b to the file "pointed" to by fptr2. Instructor: Point out that the syntax and operation of fprintf is identical to printf, except the first variable into fprintf is the file pointer it will print to. Also the file must be open for writing. Narrator: Now that reading from files has been covered, it is useful to be able to also write to files. The fprintf command, much like printf, allows the programmer to write data to a file. Its format is nearly identical to printf, except the first argument must now be the file pointer of the open file the program should write to. In the given example the fprintf writes to the file assigned to fptr2, which has been opened in write mode. The values of the variables a and b are written to the file, with a new line appended after this data. Lecture 07

15 Closing Files The statements: fclose ( fptr1 ) ; fclose ( fptr2 ) ;
Engineering H192 Winter 2005 Closing Files The statements: fclose ( fptr1 ) ; fclose ( fptr2 ) ; will close the files and release the file descriptor space and I/O buffer memory. Instructor: Once a file pointer is closed it can be used to open another file. Narrator: A method exists for closing files besides allowing the program to terminate. The fclose statement properly closes the file pointed to by the pointer included as an argument. This pointer is then freed for use again in another fopen command. This is especially useful in a program that may run for a long time and open a large number of files, so file pointers can be re-used and not fill memory with unnecessary information. Lecture 07

16 Reading and Writing Files
Engineering H192 Winter 2005 Reading and Writing Files #include <stdio.h> int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ; fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ; fclose (outfile) ; Instructor/Narrator: The next two slides contain a full program with file input and output and the output of the program at the end of the next slide. This program also introduces additional formatting of the fprintf string. When formatting data a certain number of spaces on the screen can be reserved and the precision of decimal number displayed can be chosen. This is best described by an example: %6.2f reserves 6 total spaces on the screen (including a decimal point for floats) and displays 2 decimal points of precision. In the case data that doesn’t fit (such as 9.1) zeros are appended to fill the number of decimal places and spaces added on the left to fill the number of total characters (so this would appear as “ 9.10”). In the case of integer numbers, the number of characters reserved is the only option available (such as the %2d in the given example). Lecture 07

17 Reading and Writing Files
Engineering H192 Winter 2005 Reading and Writing Files infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ; printf ("%6.2f%2d%5.2f\n", a, b, c) ; printf ("%6.2f,%2d,%5.2f\n", e, f, g) ; } **************************** 13.72, 5, 6.68 Instructor/Narrator: This program writes some pre-determined values to a file, then reads them from the file and displays them on the screen. Take some time and look over each line of the program and make sure you understand what each is doing. The original values are displayed without commas, and the data read from the file is displayed on the second line with commas as separators. Notice the same spacing of each value occurs, and the commas occur as static characters (which extend the line further). Lecture 07

18 Closing a file The input output library supports the function to close a file; it is in the following format. fclose(file_pointer); A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer. Observe the following program. …. FILE *p1 *p2; p1=fopen (“Input”,”w”); p2=fopen (“Output”,”r”); …. fclose(p1); fclose(p2) ;

19 Reading & writing getc and putc functions
The getc and putc functions are analogous to getchar and putchar functions and handle one character at a time. The putc function writes the character contained in character variable c to the file associated with the pointer fp1. Example putc(c,fp1); The getc function is used to read a character from a file that has been open in read mode. c=getc(fp2).

20 Example #include< stdio.h > main() { file *f1; printf(“Data input output”); f1=fopen(“Input”,”w”); /*Open the file Input*/ while((c=getchar())!=EOF) /*get a character from key board*/ putc(c,f1); /*write a character to input*/ fclose(f1); /*close the file input*/ printf(“nData outputn”); f1=fopen(“INPUT”,”r”); /*Reopen the file input*/ while((c=getc(f1))!=EOF) printf(“%c”,c); fclose(f1); } Check for feof and ferror functions End_of_File

21 Reading & writing The getw and putw functions
These are integer-oriented functions. They are similar to get c and putc functions and are used to read and write integer values. These functions would be usefull when we deal with only integer data. The general forms of getw and putw are: putw(integer,fp); getw(fp);

22 Reading & writing The getw and putw functions
/*Example program for using getw and putw functions*/ #include< stdio.h > main() { FILE *f1,*f2,*f3; int number I; printf(“Contents of the data filenn”); f1=fopen(“DATA”,”W”); for(I=1;I< 30;I++) { scanf(“%d”,&number); if(number==-1) break; putw(number,f1); } fclose(f1); f1=fopen(“DATA”,”r”); f2=fopen(“ODD”,”w”); f3=fopen(“EVEN”,”w”); while((number=getw(f1))!=EOF)/* Read from data file*/ { if(number%2==0) putw(number,f3);/*Write to even file*/ else putw(number,f2);/*write to odd file*/ } fclose(f1); fclose(f2); fclose(f3); f2=fopen(“ODD”,”r”); f3=fopen(“EVEN”,”r”); printf(“nnContents of the odd filenn”); while(number=getw(f2))!=EOF) printf(“%d%d”,number); printf(“nnContents of the even file”); while(number=getw(f3))!=EOF) printf(“%d”,number); fclose(f2); fclose(f3); }

23 fprintf & fscanf functions
The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files. The first argument of theses functions is a file pointer which specifies the file to be used. The general form of fprintf is fprintf(fp,”control string”, list); Where fp id a file pointer associated with a file that has been opened for writing. The control string is file output specifications list may include variable, constant and string. fprintf(f1,%s%d%f”,name,age,7.5); Here name is an array variable of type char and age is an int variable

24 fprintf & fscanf functions
The general format of fscanf is fscanf(fp,”controlstring”,list); This statement would cause the reading of items in the control string. Example: fscanf(f2,”5s%d”,item,&quantity”); Like scanf, fscanf also returns the number of items that are successfully read.

25 /*Program to handle mixed data types*/
#include< stdio.h > main() { FILE *fp; int num,qty,I; float price,value; char item[10],filename[10]; printf(“Input filename”); scanf(“%s”,filename); fp=fopen(filename,”w”); printf(“Input inventory datann”0; printf(“Item namem number price quantityn”); for I=1;I< =3;I++) { fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality); fprintf(fp,”%s%d%f%d”,itemnumber,price,quality); } fclose (fp); fprintf(stdout,”nn”); fp=fopen(filename,”r”); printf(“Item name number price quantity value”); for(I=1;I< =3;I++) { fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality); value=price*quantity”); fprintf(“stdout,”%s%d%f%d%dn”,item,number,price,quantity,value); } fclose(fp); }

26 Random access to files Sometimes it is required to access only a particular part and not the complete file. This can be accomplished by using the following function: fseek function: The general format of fseek function is a s follows: fseek(file pointer,offset, position);

27 Random access to files This function is used to move the file position to a desired location within the file. Fileptr is a pointer to the file concerned. Offset is a number or variable of type long, and position in an integer number. Offset specifies the number of positions (bytes) to be moved from the location specified by the position. The position can take the 3 values. Value Meaning 0 Beginning of the file 1 Current position 2 End of the file.

28 The Preprocessor The #include Preprocessor Directive
The #define Preprocessor Directive: Symbolic Constants The #define Preprocessor Directive: Macros Conditional Compilation The #error and #pragma Preprocessor Directives The # and ## Operators Line Numbers Predefined Symbolic Constants Assertions

29 Introduction Preprocessing Occurs before program compiled
Inclusion of external files Definition of symbolic constants Macros Conditional compilation Conditional execution All directives begin with # Can only have whitespace before directives Directives not C statements Do not end with ;

30 The #include Preprocessor Directive
#include directive Puts copy of file in place of directive Seen many times in example code Two forms #include <filename> For standard library header files Searches predesignated directories #include "filename" Searches in current directory Normally used for programmer-defined files

31 The #include Preprocessor Directive
Usage Loading header files #include <iostream> Programs with multiple source files Header file Has common declarations and definitions Classes, structures, enumerations, function prototypes Extract commonality of multiple program files

32 The #define Preprocessor Directive: Symbolic Constants
Constants represented as symbols When program compiled, all occurrences replaced Format #define identifier replacement-text #define PI Everything to right of identifier replaces text #define PI= Replaces PI with "= " Probably an error Cannot redefine symbolic constants

33 The #define Preprocessor Directive: Symbolic Constants
Advantages Takes no memory Disadvantages Name not be seen by debugger (only replacement text) Do not have specific data type const variables preferred

34 The #define Preprocessor Directive: Macros
Operation specified in #define Intended for legacy C programs Macro without arguments Treated like a symbolic constant Macro with arguments Arguments substituted for replacement text Macro expanded Performs a text substitution No data type checking

35 The #define Preprocessor Directive: Macros
Example #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) ) area = CIRCLE_AREA( 4 ); becomes area = ( * ( 4 ) * ( 4 ) ); Use parentheses Without them, #define CIRCLE_AREA( x ) PI * x * x area = CIRCLE_AREA( c + 2 ); area = * c + 2 * c + 2; which evaluates incorrectly

36 The #define Preprocessor Directive: Macros
Multiple arguments #define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) ) rectArea = RECTANGLE_AREA( a + 4, b + 7 ); becomes rectArea = ( ( a + 4 ) * ( b + 7 ) ); #undef Undefines symbolic constant or macro Can later be redefined

37 Conditional Compilation
Control preprocessor directives and compilation Cannot evaluate cast expressions, sizeof, enumeration constants Structure similar to if #if !defined( NULL ) #define NULL 0 #endif Determines if symbolic constant NULL defined If NULL defined, defined( NULL ) evaluates to 1 #define statement skipped Otherwise #define statement used Every #if ends with #endif

38 Conditional Compilation
Can use else #else #elif is "else if" Abbreviations #ifdef short for #if defined(name) #ifndef short for #if !defined(name)

39 Conditional Compilation
"Comment out" code Cannot use /* ... */ with C-style comments Cannot nest /* */ Instead, use #if 0 code commented out #endif To enable code, change 0 to 1

40 Conditional Compilation
Debugging #define DEBUG 1 #ifdef DEBUG cerr << "Variable x = " << x << endl; #endif Defining DEBUG enables code After code corrected Remove #define statement Debugging statements are now ignored

41 The #error and #pragma Preprocessor Directives
#error tokens Prints implementation-dependent message Tokens are groups of characters separated by spaces #error 1 - Out of range error has 6 tokens Compilation may stop (depends on compiler) #pragma tokens Actions depend on compiler May use compiler-specific options Unrecognized #pragmas are ignored

42 The # and ## Operators # operator ## operator
Replacement text token converted to string with quotes #define HELLO( x ) cout << "Hello, " #x << endl; HELLO( JOHN ) becomes cout << "Hello, " "John" << endl; Same as cout << "Hello, John" << endl; ## operator Concatenates two tokens #define TOKENCONCAT( x, y ) x ## y TOKENCONCAT( O, K ) becomes OK

43 Line Numbers #line Renumbers subsequent code lines, starting with integer #line 100 File name can be included #line 100 "file1.c" Next source code line is numbered 100 For error purposes, file name is "file1.c" Can make syntax errors more meaningful Line numbers do not appear in source file

44 Predefined Symbolic Constants
Five predefined symbolic constants Cannot be used in #define or #undef

45 Assertions assert is a macro To remove assert statements
Header <cassert> Tests value of an expression If 0 (false) prints error message, calls abort Terminates program, prints line number and file Good for checking for illegal values If 1 (true), program continues as normal assert( x <= 10 ); To remove assert statements No need to delete them manually #define NDEBUG All subsequent assert statements ignored

46 Preprocessing language
The preprocessing language After tokenization, the stream of tokens may simply be passed straight to the compiler’s parser. However, if it contains any operations in the preprocessing language, it will be transformed first. This stage corresponds roughly to the standard’s “translation phase 4” and is what most people think of as the preprocessor’s job. The preprocessing language consists of directives to be executed and macros to be expanded.Its primary capabilities are: Inclusion of header files. These are files of declarations that can be substituted into your program. Macro expansion. You can define macros, which are abbreviations for arbitrary fragments of C code. The preprocessor will replace the macros with their definitions throughout the program. Some macros are automatically defined for you. Conditional compilation. You can include or exclude parts of the program according to various conditions. Line control. If you use a program to combine or rearrange source files into an intermediate file which is then compiled, you can use line control to inform the compiler where each source line originally came from. Diagnostics. You can detect problems at compile time and issue errors or warnings.

47 Header Files int x; char *test (void); Int main (void)
Include Syntax( #include <file> or #include "file" Suppose the file myfile.h contains the statement char *test (void); and the program file program.c’ contains\ int x; char *test (void); Int main (void) {puts (test ()); } int x; #include “myfile.h" int main (void) { puts (test ()); }

48 Search Path for include files
/usr/local/include libdir/gcc/target/version/include /usr/target/include /usr/include

49 Macros foo = (char *) malloc (1024);
A macro is a fragment of code which has been given a name. An object-like macro is a simple identifier which will be replaced by a code fragment. Create macros with the ‘#define’ directive. #define BUFFER_SIZE 1024 foo = (char *) malloc (BUFFER_SIZE); foo = (char *) malloc (1024);

50 Macros int x[] = { 1, 2, 3 }; #define NUMBERS 1, \ 2, \ 3
int x[] = { NUMBERS }; Macro can be declared using multiple lines It is equivalent to int x[] = { 1, 2, 3 };

51 Macros fax= X; #define X 4 bar = X; produces fax = X; bar = 4;
#define TABLESIZE BUFSIZE #define BUFSIZE 1024 TABLESIZE BUFSIZE 1024 TABLESIZE is expanded first to produce BUFSIZE, then that macro is expanded to produce the final result, 1024.

52 Macros undefine #define BUFSIZE 1020 #define TABLESIZE BUFSIZE
#undef BUFSIZE #define BUFSIZE 37 Now TABLESIZE expands (in two stages) to 37.

53 Function-like Macros c_init() #define lang_init() c_init() lang_init()
A function-like macro is only expanded if its name appears with a pair of parentheses after it. If you write just the name, it is left alone. This can be useful when you have a function and a macro of the same name, and you wish to use the function sometimes. c_init() extern void foo(void); #define foo() /* optimized inline version */ ... foo(); funcptr = foo; The call to foo() will use the macro The function pointer will get the address of the real function.

54 #define lang_init () c_init() lang_init()
Function-like Macros #define lang_init () c_init() lang_init() There should not be blank If blank then lang_init() will expand to () c_init()()

55 Macro Arguments #define min(X, Y) ((X) < (Y) ? (X) : (Y))
x = min(a, b);  x = ((a) < (b) ? (a) : (b)); y = min(1, 2);  y = ((1) < (2) ? (1) : (2)); z = min(a + 28, *p);  z = ((a + 28) < (*p) ? (a + 28): (*p)); Example min (min (a, b), c) is first expanded to min (((a) < (b) ? (a) : (b)), (c)) and then to ((((a) < (b) ? (a) : (b))) < (c) ? (((a) < (b) ? (a) : (b))) : (c))

56 Stringification (#) Convert a macro argument into a string constant.
#define WARN_IF(EXP) \ do { if (EXP) \ fprintf (stderr, "Warning: " #EXP "\n"); } \ while (0) WARN_IF (x == 0);  do { if (x == 0) fprintf (stderr, "Warning: " "x == 0" "\n"); } while (0);

57 xstr (foo)  xstr (4)  str (4)  "4"
Stringification (#) #define xstr(s) str(s) #define str(s) #s #define foo 4 str (foo)  "foo" xstr (foo)  xstr (4)  str (4)  "4"

58 Concatenation ‘##’ This is called token pasting or token concatenation. The ‘##’ preprocessing operator performs token pasting. When a macro is expanded, the two tokens on either side of each ‘##’ operator are combined into a single token, which then replaces the ‘##’ and the two original tokens in the macro expansion. struct command { char *name; void (*function) (void); }; struct command commands[] = { { "quit", quit_command }, { "help", help_command }, ... #define COMMAND(NAME) { #NAME, NAME ## _command } struct command commands[] = { COMMAND (quit), COMMAND (help), ... };

59 Predefined Macros __FILE__
This macro expands to the name of the current input file, in the form of a C string constant. This macro expands to the current input line number, in the form of a decimal integer constant. __LINE__ __DATE__ This macro expands to a string constant that describes the date on which the preprocessor is being run. The string constant contains eleven characters and looks like "Feb ". __TIME__ This macro expands to a string constant that describes the time at which the preprocessor is being run. The string constant contains eight characters and looks like "23:59:01".

60 Undefining and Redefining Macros
#define FOO 4 x = FOO;  x = 4; #undef FOO x = FOO;  x = FOO;

61 Conditional Syntax #ifdef MACRO controlled text #endif /* MACRO */
#if expression controlled text #endif /* expression */ #if X == 1 ... #elif X == 2 #else /* X != 2 and X != 1*/ #endif /* X != 2 and X != 1*/ #if X == 1 ... #else /* X != 1 */ #if X == 2 #else /* X != 2 */ #endif /* X != 2 */ #endif /* X != 1 */ #if defined MACRO is precisely equivalent to #ifdef MACRO. Elif #if expression text-if-true #else /* Not expression */ text-if-false #endif /* Not expression */

62 #Pragmas The ‘#pragma’ directive is the method specified by the C standard for providing additional information to the compiler. It is an implementation oriented directive. #pragma loop_opt(on) causes loop optimization in a program #error The ‘#error’ produces error messages during debugging. #if !defined(FILE_GRAPHICS) #error NO GRAPHICS FACILITY #endif.

Download ppt "Files in C Rohit Khokher."

Similar presentations

Ads by Google