Happy Codings - Programming Code Examples

C Programming Code Examples

C > File Operations Code Examples

C language file operations - Open, read, write and close operation in C

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
/* C language file operations - Open, read, write and close operation in C The fclose( ) function is used for closing an opened file. As an argument you must provide a pointer to the file that you want to close. An example to show Open, read, write and close operation in C */ #include <stdio.h> int main() { char ch; /* Pointer for both the file*/ FILE *fpr, *fpw; /* Opening file FILE1.C in "r" mode for reading */ fpr = fopen("C:\\file1.txt", "r"); /* Ensure FILE1.C opened successfully*/ if (fpr == NULL) { puts("Input file cannot be opened"); } /* Opening file FILE2.C in "w" mode for writing*/ fpw= fopen("C:\\file2.txt", "w"); /* Ensure FILE2.C opened successfully*/ if (fpw == NULL) { puts("Output file cannot be opened"); } /*Read & Write Logic*/ while(1) { ch = fgetc(fpr); if (ch==EOF) break; else fputc(ch, fpw); } /* Closing both the files */ fclose(fpr); fclose(fpw); return 0; }
main() Function in C
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed. Its first function or entry point of the program from where program start executed, program's execution starts from the main. So main is an important function in c , c++ programming language.
Syntax for main() Function in C
void main() { ......... // codes start from here ......... }
void
is a keyword in C language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value. In place of void we can also use int return type of main() function, at that time main() return integer type value.
main
is a name of function which is predefined function in C library. • An operating system always calls the main() function when a programmers or users execute their programming code. • It is responsible for starting and ends of the program. • It is a universally accepted keyword in programming language and cannot change its meaning and name. • A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program. • A main() function is used to invoke the programming code at the run time, not at the compile time of a program. • A main() function is followed by opening and closing parenthesis brackets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* basic c program by main() function example */ #include <stdio.h> #include <conio.h> main() { printf (" It is a main() function "); int fun2(); // jump to void fun1() function printf ("\n Finally exit from the main() function. "); } void fun1() { printf (" It is a second function. "); printf (" Exit from the void fun1() function. "); } int fun2() { void fun1(); // jump to the int fun1() function printf (" It is a third function. "); printf (" Exit from the int fun2() function. "); return 0; }
Pointers in C Language
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps. As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined:
#include <stdio.h> int main () { int var1; char var2[10]; printf("Address of var1 variable: %x\n", &var1 ); printf("Address of var2 variable: %x\n", &var2 ); return 0; }
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is:
Syntax for Pointer variable declaration in C
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declaration:
int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. There are a few important operations, which we will do with the help of pointers very frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. NULL Pointers: It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a value of zero defined in several standard libraries. In most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing. To check for a null pointer, you can use an 'if' statement as follows:
if(ptr) /* succeeds if p is not null */ if(!ptr) /* succeeds if p is null */
Pointer arithmetic: There are four arithmetic operators that can be used in pointers: ++, --, +, - Array of pointers: You can define arrays to hold a number of pointers. Pointer to pointer: C allows you to have pointer on a pointer and so on. Passing pointers to functions in C: Passing an argument by reference or by address enable the passed argument to be changed in the calling function by the called function. Return pointer from functions in C: C allows a function to return a pointer to the local variable, static variable, and dynamically allocated memory as well.
Advantage of Pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and used with arrays, structures, and functions. 2) We can return multiple values from a function using the pointer. 3) It makes you able to access any memory location in the computer's memory.
Usage of Pointer
There are many applications of pointers in c language. 1) Dynamic memory allocation: In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer is used. 2) Arrays, Functions, and Structures: Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves the performance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* working of pointers in C Language */ #include <stdio.h> int main() { int* pc, c; c = 22; printf("Address of c: %p\n", &c); printf("Value of c: %d\n\n", c); // 22 pc = &c; printf("Address of pointer pc: %p\n", pc); printf("Content of pointer pc: %d\n\n", *pc); // 22 c = 11; printf("Address of pointer pc: %p\n", pc); printf("Content of pointer pc: %d\n\n", *pc); // 11 *pc = 2; printf("Address of c: %p\n", &c); printf("Value of c: %d\n\n", c); // 2 return 0; }
close() Function in C
Closes a file descriptor, fildes. This frees the file descriptor to be returned by future open() calls and other calls that create file descriptors. The fildes argument must represent a hierarchical file system (HFS) file. When the last open file descriptor for a file is closed, the file itself is closed. If the file's link count is 0 at that time, its space is freed and the file becomes inaccessible. When the last open file descriptor for a pipe or FIFO file is closed, any data remaining in the pipe or FIFO file is discarded. close() unlocks (removes) all outstanding record locks that a process has on the associated file.
Syntax for close() Function in C
#include <unistd.h> int close(int fildes);
fildes
The descriptor of the socket to be closed. Behavior for sockets: close() call shuts down the socket associated with the socket descriptor socket, and frees resources allocated to the socket. If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed. All sockets should be closed before the end of your process. You should issue a shutdown() call before you issue a close() call for a socket. For AF_INET and AF_INET6 stream sockets (SOCK_STREAM) using SO_LINGER socket option, the socket does not immediately end if data is still present when a close is issued. The following structure is used to set or unset this option, and it can be found in sys/socket.h.
struct linger { int l_onoff; /* zero=off, nonzero=on */ int l_linger; /* time is seconds to linger */ };
If the l_onoff switch is nonzero, the system attempts to deliver any unsent messages. If a linger time is specified, the system waits for n seconds before flushing the data and terminating the socket. For AF_UNIX, when closing sockets that were bound, you should also use unlink() to delete the file created at bind() time. Special behavior for XPG4.2: If a STREAMS-based fildes is closed and the calling process was previously registered to receive a SIGPOLL signal for events associated with that STREAM, the calling process will be unregistered for events associated with the STREAM. The last close() for a STREAM causes the STREAM associated with fildes to be dismantled. If O_NONBLOCK is not set and there have been no signals posted for the STREAM, and if there is data on the module's write queue, close() waits for an unspecified time (for each module and driver) for any output to drain before dismantling the STREAM. The time delay can be changed using an I_SETCLTIME ioctl() request. If the O_NONBLOCK flag is set, or if there are any pending signals, close() does not wait for output to drain, and dismantles the STREAM immediately. Note: z/OS® UNIX services do not supply any STREAMS devices or pseudodevices. See open() - Open a file for more information. If fildes refers to the master side of a pseudoterminal, a SIGHUP signal is sent to the process group, if any, for which the slave side of the pseudoterminal is the controlling terminal. If fildes refers to the slave side of a pseudoterminal, a zero-length message will be sent to the master. If fildes refers to a socket, close() causes the socket to be destroyed. If the socket is connection-oriented and the SO_LINGER option is set for the socket and the socket has untransmitted data, then close() will block for up to the current linger interval until all data is transmitted. If successful, close() returns 0. If unsuccessful, close() returns -1 and sets errno to one of the following values:
EAGAIN
The call did not complete because the specified socket descriptor is currently being used by another thread in the same process. For example, in a multithreaded environment, close() fails and returns EAGAIN when the following sequence of events occurs (1) thread is blocked in a read() or select() call on a given file or socket descriptor and (2) another thread issues a simultaneous close() call for the same descriptor.
EBADF
fildes is not a valid open file descriptor, or the socket parameter is not a valid socket descriptor.
EBUSY
The file cannot be closed because it is blocked.
EINTR
close() was interrupted by a signal. The file may or may not be closed.
EIO
Added for XPG4.2: An I/O error occurred while reading from or writing to the file system.
ENXIO
fildes does not exist. The minor number for the file is incorrect.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* close a file descriptor by close() function code example */ #include <fcntl.h> #include <unistd.h> #include <stdlib.h> int main( void ) { int filedes; filedes = open( "file", O_RDONLY ); if( filedes != -1 ) { /* process file */ close( filedes ); return EXIT_SUCCESS; } return EXIT_FAILURE; }
getc() Function in C
Get character from stream. Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced to the next character. If the stream is at the end-of-file when called, the function returns EOF and sets the end-of-file indicator for the stream (feof). If a read error occurs, the function returns EOF and sets the error indicator for the stream (ferror). getc and fgetc are equivalent, except that getc may be implemented as a macro in some libraries. See getchar for a similar function that reads directly from stdin.
Syntax for getc() Function in C
#include <stdio.h> int getc ( FILE * stream );
stream
Pointer to a FILE object that identifies an input stream. Because some libraries may implement this function as a macro, and this may evaluate the stream expression more than once, this should be an expression without side effects. On success, the character read is returned (promoted to an int value). The return type is int to accommodate for the special value EOF, which indicates failure: If the position indicator was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stream. If some other reading error happens, the function also returns EOF, but sets its error indicator (ferror) instead. The getc function in C reads the next character from any input stream and returns an integer value. It is a standard function in C and can be used by including the <stdio.h> header file. The getc() function can be implemented as a macro whereas fgetc() function can not be used as macro. Also getc() function is highly optimized and hence calls to fgetc() probably take longer than calls to getc(). So, getc() is preferred in most situations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/* read a single character from the current stream position and advance the stream position to the next character by getc() function example. */ #include <stdio.h> #include <stdlib.h> int main() { //Initialize the file pointer FILE* f; char ch; //Create the file for write operation f = fopen("myfile.txt", "w"); printf("Enter five character\n"); for (int i = 0; i < 5; i++) { //take the characters from the users scanf("%c", &ch); //write back to the file putc(ch, f); //clear the stdin stream buffer fflush(stdin); } //close the file after write operation is over fclose(f); //open a file f = fopen("myfile.txt", "r"); printf("Write operation is over and file is ready for read operation\n"); printf("\n...............print the characters..............\n\n"); while (!feof(f)) { //takes the characters in the character array ch = getc(f); //and print the characters printf("%c\n", ch); } fclose(f); return 0; }
fclose() Function in C
Close file. Closes the file associated with the stream and disassociates it. All internal buffers associated with the stream are disassociated from it and flushed: the content of any unwritten output buffer is written and the content of any unread input buffer is discarded. Even if the call fails, the stream passed as parameter will no longer be associated with the file nor its buffers.
Syntax for fclose() Function in C
#include <stdio.h> int fclose ( FILE * stream );
stream
Pointer to a FILE object that specifies the stream to be closed. The fclose() function shall cause the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream shall be written to the file; any unread buffered data shall be discarded. Whether or not the call succeeds, the stream shall be disassociated from the file and any buffer set by the setbuf() or setvbuf() function shall be disassociated from the stream. If the associated buffer was automatically allocated, it shall be deallocated. After the call to fclose(), any use of stream results in undefined behavior. If the stream is successfully closed, a zero value is returned. On failure, EOF is returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* close the file associated with the stream and disassociates it by close() function example */ /* Open, write and close a file : */ # include <stdio.h> # include <string.h> int main( ) { FILE *fp ; char data[50]; // opening an existing file printf( "Opening the file test.c in write mode" ) ; fp = fopen("test.c", "w") ; if ( fp == NULL ) { printf( "Could not open file test.c" ) ; return 1; } printf( "\n Enter some text from keyboard" \ " to write in the file test.c" ) ; // getting input from user while ( strlen ( gets( data ) ) > 0 ) { // writing in the file fputs(data, fp) ; fputs("\n", fp) ; } // closing the file printf("Closing the file test.c") ; fclose(fp) ; return 0; }
open() Function in C
The open() function shall establish the connection between a file and a file descriptor. It shall create an open file description that refers to a file and a file descriptor that refers to that open file description. The file descriptor is used by other I/O functions to refer to that file. The path argument points to a pathname naming the file. The open() function shall return a file descriptor for the named file that is the lowest file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor shall not share it with any other process in the system. The FD_CLOEXEC file descriptor flag associated with the new file descriptor shall be cleared.
Syntax for open() Function in C
#include <fcntl.h> int open(const char *path, int oflag, ... );
path
path to file which you want to use
oflag
How you like to use The file offset used to mark the current position within the file shall be set to the beginning of the file. The file status flags and file access modes of the open file description shall be set according to the value of oflag. Values for oflag are constructed by a bitwise-inclusive OR of flags from the following list, defined in <fcntl.h>. Applications shall specify exactly one of the first three values (file access modes) below in the value of oflag:
O_RDONLY
Open for reading only.
O_WRONLY
Open for writing only.
O_RDWR
Open for reading and writing. The result is undefined if this flag is applied to a FIFO. Any combination of the following may be used:
O_APPEND
If set, the file offset shall be set to the end of the file prior to each write.
O_CREAT
If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, the file shall be created; the user ID of the file shall be set to the effective user ID of the process; the group ID of the file shall be set to the group ID of the file's parent directory or to the effective group ID of the process; and the access permission bits (see <sys/stat.h>) of the file mode shall be set to the value of the third argument taken as type mode_t modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared. When bits other than the file permission bits are set, the effect is unspecified. The third argument does not affect whether the file is open for reading, writing, or for both. Implementations shall provide a way to initialize the file's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the file's group ID to the effective group ID of the calling process.
O_DSYNC
Write I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion.
O_EXCL
If O_CREAT and O_EXCL are set, open() shall fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist shall be atomic with respect to other threads executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set, and path names a symbolic link, open() shall fail and set errno to [EEXIST], regardless of the contents of the symbolic link. If O_EXCL is set and O_CREAT is not set, the result is undefined.
O_NOCTTY
If set and path identifies a terminal device, open() shall not cause the terminal device to become the controlling terminal for the process.
O_NONBLOCK
When opening a FIFO with O_RDONLY or O_WRONLY set: • If O_NONBLOCK is set, an open() for reading-only shall return without delay. An open() for writing-only shall return an error if no process currently has the file open for reading. • If O_NONBLOCK is clear, an open() for reading-only shall block the calling thread until a thread opens the file for writing. An open() for writing-only shall block the calling thread until a thread opens the file for reading. When opening a block special or character special file that supports non-blocking opens: • If O_NONBLOCK is set, the open() function shall return without blocking for the device to be ready or available. Subsequent behavior of the device is device-specific. • If O_NONBLOCK is clear, the open() function shall block the calling thread until the device is ready or available before returning. Otherwise, the behavior of O_NONBLOCK is unspecified.
O_RSYNC
Read I/O operations on the file descriptor shall complete at the same level of integrity as specified by the O_DSYNC and O_SYNC flags. If both O_DSYNC and O_RSYNC are set in oflag, all I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If both O_SYNC and O_RSYNC are set in flags, all I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.
O_SYNC
Write I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.
O_TRUNC
If the file exists and is a regular file, and the file is successfully opened O_RDWR or O_WRONLY, its length shall be truncated to 0, and the mode and owner shall be unchanged. It shall have no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-defined. The result of using O_TRUNC with O_RDONLY is undefined. If O_CREAT is set and the file did not previously exist, upon successful completion, open() shall mark for update the st_atime, st_ctime, and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory. If O_TRUNC is set and the file did previously exist, upon successful completion, open() shall mark for update the st_ctime and st_mtime fields of the file. If both the O_SYNC and O_DSYNC flags are set, the effect is as if only the O_SYNC flag was set. If path refers to a STREAMS file, oflag may be constructed from O_NONBLOCK OR'ed with either O_RDONLY, O_WRONLY, or O_RDWR. Other flag values are not applicable to STREAMS devices and shall have no effect on them. The value O_NONBLOCK affects the operation of STREAMS drivers and certain functions applied to file descriptors associated with STREAMS files. For STREAMS drivers, the implementation of O_NONBLOCK is device-specific. If path names the master side of a pseudo-terminal device, then it is unspecified whether open() locks the slave side so that it cannot be opened. Conforming applications shall call unlockpt() before opening the slave side. The largest value that can be represented correctly in an object of type off_t shall be established as the offset maximum in the open file description. Upon successful completion, the function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error. No files shall be created or modified if the function returns -1. The open() function shall fail if:
EACCES
Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by oflag are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created, or O_TRUNC is specified and write permission is denied.
EEXIST
O_CREAT and O_EXCL are set, and the named file exists.
EINTR
A signal was caught during open().
EINVAL
The implementation does not support synchronized I/O for this file.
EIO
The path argument names a STREAMS file and a hangup or error occurred during the open().
EISDIR
The named file is a directory and oflag includes O_WRONLY or O_RDWR.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENFILE
The maximum allowable number of files is currently open in the system.
ENOENT
O_CREAT is not set and the named file does not exist; or O_CREAT is set and either the path prefix does not exist or the path argument points to an empty string.
ENOSR
The path argument names a STREAMS-based file and the system is unable to allocate a STREAM.
ENOSPC
The directory or file system that would contain the new file cannot be expanded, the file does not exist, and O_CREAT is specified.
ENOTDIR
A component of the path prefix is not a directory.
ENXIO
O_NONBLOCK is set, the named file is a FIFO, O_WRONLY is set, and no process has the file open for reading.
ENXIO
The named file is a character special or block special file, and the device associated with this special file does not exist.
EOVERFLOW
The named file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.
EROFS
The named file resides on a read-only file system and either O_WRONLY, O_RDWR, O_CREAT (if the file does not exist), or O_TRUNC is set in the oflag argument. The open() function may fail if:
EAGAIN
The path argument names the slave side of a pseudo-terminal device that is locked.
EINVAL
The value of the oflag argument is not valid.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.
ENOMEM
The path argument names a STREAMS file and the system is unable to allocate resources.
ETXTBSY
The file is a pure procedure (shared text) file that is being executed and oflag is O_WRONLY or O_RDWR.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/* open or create a file for reading, writing or executing by open() function code example */ // C program to illustrate // open system call #include<stdio.h> #include<fcntl.h> #include<errno.h> extern int errno; int main() { // if file does not have in directory // then file foo.txt is created. int fd = open("foo.txt", O_RDONLY | O_CREAT); printf("fd = %d/n", fd); if (fd ==-1) { // print which type of error have in a code printf("Error Number % d\n", errno); // print program detail "Success or failure" perror("Program"); } return 0; }
puts() Function in C
Write string to stdout. Writes the C string pointed by str to the standard output (stdout) and appends a newline character ('\n'). The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This terminating null-character is not copied to the stream. Notice that puts not only differs from fputs in that it uses stdout as destination, but it also appends a newline character at the end automatically (which fputs does not). The puts() function is very much similar to printf() function. The puts() function is used to print the string on the console which is previously read by using gets() or scanf() function. The puts() function returns an integer value representing the number of characters being printed on the console. Since, it prints an additional newline character with the string, which moves the cursor to the new line on the console, the integer value returned by puts() will always be equal to the number of characters present in the string plus 1.
Syntax for puts() Function in C
#include <stdio.h> int puts(const char *str)
str
C string to be printed. On success, a non-negative value is returned. On error, the function returns EOF and sets the error indicator (ferror).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* write string to stdout by puts() function example */ #include <stdio.h> #include <string.h> int main() { char name[50]; printf("Enter your name "); gets(name); int age[50]; printf("Enter your age "); gets(age); char address[50]; printf("Enter your address "); gets(address); int pincode[50]; printf("Enter your pincode "); gets(pincode); printf("Entered Name is: "); puts(name); printf("Entered age is: "); puts(age); printf("Entered address is: "); puts(address); printf("Entered pincode is: "); puts(pincode); getch(); return 0; }
Break Statement in C
The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.
Syntax for Break Statement in C
//loop statement... break;
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter). If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/* bring the program control out of the loop by break keyword */ // Program to calculate the sum of numbers (10 numbers max) // If the user enters a negative number, the loop terminates #include <stdio.h> int main() { int i; double number, sum = 0.0; for (i = 1; i <= 10; ++i) { printf("Enter n%d: ", i); scanf("%lf", &number); // if the user enters a negative number, break the loop if (number < 0.0) { break; } sum += number; // sum = sum + number; } printf("Sum = %.2lf", sum); return 0; }
putc() Function in C
Write character to stream. Writes a character to the stream and advances the position indicator. The character is written at the position indicated by the internal position indicator of the stream, which is then automatically advanced by one. putc and fputc are equivalent, except that putc may be implemented as a macro in some libraries. See putchar for a similar function that writes directly to stdout.
Syntax for putc() Function in C
#include <stdio.h> int putc ( int character, FILE * stream );
character
The int promotion of the character to be written. The value is internally converted to an unsigned char when written. Because some libraries may implement this function as a macro, and this may evaluate the stream expression more than once, this should be an expression without side effects.
stream
Pointer to a FILE object that identifies an output stream. On success, the character written is returned. If a writing error occurs, EOF is returned and the error indicator (ferror) is set. putc() function is C library function, and it's used to write a character to the file. This function is used for writing a single character in a stream along with that it moves forward the indicator's position.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
/* write a character to an output stream by putc() function example */ #include <stdio.h> #include <stdlib.h> int main() { //Initialize the file pointer FILE* f; char ch; //Create the file for write operation f = fopen("myfile.txt", "w"); printf("Enter five character\n"); for (int i = 0; i < 5; i++) { //take the characters from the users scanf("%c", &ch); //write back to the file putc(ch, f); //clear the stdin stream buffer fflush(stdin); } //close the file after write operation is over fclose(f); //open a file f = fopen("myfile.txt", "r"); printf("Write operation is over and file is reday for read operation\n"); printf("\n...............print the characters..............\n\n"); while (!feof(f)) { //takes the characters in the character array ch = getc(f); //and print the characters printf("%c\n", ch); } fclose(f); return 0; }
While Loop Statement in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.
Syntax of While Loop Statement in C
while (testExpression) { // the body of the loop }
• The while loop evaluates the testExpression inside the parentheses (). • If testExpression is true, statements inside the body of while loop are executed. Then, testExpression is evaluated again. • The process goes on until testExpression is evaluated to false. • If testExpression is false, the loop terminates (ends).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* while loop statement in C language */ #include<stdio.h> int main() { int n, num, sum = 0, remainder; printf("Enter a number: "); scanf("%d", &n); num = n; // keep looping while n > 0 while( n > 0 ) { remainder = n % 10; // get the last digit of n sum += remainder; // add the remainder to the sum n /= 10; // remove the last digit from n } printf("Sum of digits of %d is %d", num, sum); // signal to operating system everything works fine return 0; }
If Else Statement in C
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
Syntax for if-else Statement in C
if (test expression) { // run code if test expression is true } else { // run code if test expression is false }
If the test expression is evaluated to true, • statements inside the body of if are executed. • statements inside the body of else are skipped from execution. If the test expression is evaluated to false, • statements inside the body of else are executed • statements inside the body of if are skipped from execution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* if else statement in C language */ // Check whether an integer is odd or even #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); // True if the remainder is 0 if (number%2 == 0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; }
fopen() Function in C
Open file. Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE pointer returned. The operations that are allowed on the stream and how these are performed are defined by the mode parameter. The returned stream is fully buffered by default if it is known to not refer to an interactive device (see setbuf). The returned pointer can be disassociated from the file by calling fclose or freopen. All opened files are automatically closed on normal program termination. The running environment supports at least FOPEN_MAX files open simultaneously.
Syntax for fopen() Function in C
#include <stdio.h> FILE * fopen ( const char * filename, const char * mode );
filename
C string containing the name of the file to be opened. Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).
mode
C string containing a file access mode. It can be:
r read
Open file for input operations. The file must exist.
w write
Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
a append
Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.
r+ read/update
Open a file for update (both for input and output). The file must exist.
w+ write/update
Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.
a+ append/update
Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist. With the mode specifiers above the file is open as a text file. In order to open a file as a binary file, a "b" character has to be included in the mode string. This additional "b" character can either be appended at the end of the string (thus making the following compound modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+"). The new C standard (C2011, which is not part of C++) adds a new standard subspecifier ("x"), that can be appended to any "w" specifier (to form "wx", "wbx", "w+x" or "w+bx"/"wb+x"). This subspecifier forces the function to fail if the file exists, instead of overwriting it. If additional characters follow the sequence, the behavior depends on the library implementation: some implementations may ignore additional characters so that for example an additional "t" (sometimes used to explicitly state a text file) is accepted. On some library implementations, opening or creating a text file with update mode may treat the stream instead as a binary file. Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability. For files open for update (those which include a "+" sign), on which both input and output operations are allowed, the stream shall be flushed (fflush) or repositioned (fseek, fsetpos, rewind) before a reading operation that follows a writing operation. The stream shall be repositioned (fseek, fsetpos, rewind) before a writing operation that follows a reading operation (whenever that operation did not reach the end-of-file). If the file is successfully opened, the function returns a pointer to a FILE object that can be used to identify the stream on future operations. Otherwise, a null pointer is returned. On most library implementations, the errno variable is also set to a system-specific error code on failure.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* open the file specified by filename and associates a stream with it by fopen() function example */ /* Open, write and close a file : */ # include <stdio.h> # include <string.h> int main( ) { FILE *fp ; char data[50]; // opening an existing file printf( "Opening the file test.c in write mode" ) ; fp = fopen("test.c", "w") ; if ( fp == NULL ) { printf( "Could not open file test.c" ) ; return 1; } printf( "\n Enter some text from keyboard" \ " to write in the file test.c" ) ; // getting input from user while ( strlen ( gets( data ) ) > 0 ) { // writing in the file fputs(data, fp) ; fputs("\n", fp) ; } // closing the file printf("Closing the file test.c") ; fclose(fp) ; return 0; }
#include Directive in C
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include: • Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. • User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor.
Syntax for #include Directive in C
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* #include directive tells the preprocessor to insert the contents of another file into the source code at the point where the #include directive is found. */ // C program to illustrate file inclusion // <> used to import system header file #include <stdio.h> // " " used to import user-defined file #include "process.h" // main function int main() { // add function defined in process.h add(10, 20); // mult function defined in process.h multiply(10, 20); // printf defined in stdio.h printf("Process completed"); return 0; }
fgetc() Function in C
Get character from stream. Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced to the next character. If the stream is at the end-of-file when called, the function returns EOF and sets the end-of-file indicator for the stream (feof). If a read error occurs, the function returns EOF and sets the error indicator for the stream (ferror). fgetc and getc are equivalent, except that getc may be implemented as a macro in some libraries.
Syntax for fgetc() Function in C
#include <stdio.h> int fgetc ( FILE * stream );
stream
Pointer to a FILE object that identifies an input stream. fgetc() is used to obtain input from a file single character at a time. This function returns the ASCII code of the character read by the function. It returns the character present at position indicated by file pointer. After reading the character, the file pointer is advanced to next character. If pointer is at end of file or if an error occurs EOF file is returned by this function. On success, the character read is returned (promoted to an int value). The return type is int to accommodate for the special value EOF, which indicates failure: If the position indicator was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stream. If some other reading error happens, the function also returns EOF, but sets its error indicator (ferror) instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/* get character from stream by fgetc() function example */ /* Open, Read and close a file: Reading char by char */ # include <stdio.h> int main( ) { FILE *fp ; char c ; printf( "Opening the file test.c in read mode" ) ; fp = fopen ( "test.c", "r" ) ; // opening an existing file if ( fp == NULL ) { printf ( "Could not open file test.c" ) ; return 1; } printf( "Reading the file test.c" ) ; while ( 1 ) { c = fgetc ( fp ) ; // reading the file if ( c == EOF ) break ; printf ( "%c", c ) ; } printf("Closing the file test.c") ; fclose ( fp ) ; // Closing the file return 0; }
fputc() Function in C
Write character to stream. Writes a character to the stream and advances the position indicator. The character is written at the position indicated by the internal position indicator of the stream, which is then automatically advanced by one. fputc() function is a file handling function in C programming language which is used to write a character into a file. It writes a single character at a time in a file and moves the file pointer position to the next address/location to write the next character.
Syntax for fputc() Function in C
#include <stdio.h> int fputc ( int character, FILE * stream );
character
The int promotion of the character to be written. The value is internally converted to an unsigned char when written.
stream
Pointer to a FILE object that identifies an output stream. On success, the character written is returned. If a writing error occurs, EOF is returned and the error indicator (ferror) is set.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* write a character to the stream and advance the position indicator by fputc() function example */ #include<stdio.h> #include<stdlib.h> int main() { int ch; FILE *fp; fp = fopen("myfile.txt", "w"); if(fp == NULL) { printf("Error opening file\n"); exit(1); } printf("Press Ctrl+Z in DOS and Ctrl+D\n\ in Linux to stop reading more characters\n\n"); printf("Enter text: "); while( (ch=getchar()) != EOF ) { fputc(ch, fp); } fclose(fp); return 0; }


Dynamic string arrays in C language. Print the array of strings. Free the string array, Note: You must delete each individual string before you delete the array of pointers...
C programming code to Mailing list. Initialize the structure array. Initialize the list. Get a menu selection. Input addresses into the list. Find an unused structure. Delete an address.
If the list is empty, create first node. Go to last node. Add node at the end. Preform a bubble sort on the linked list. The 'c' node precedes the 'a' and 'e' node pointing up...
Create menu driven Calculator that performs basic mathematic operations (Add, Subtract, Multiply, Divide) use switch case & functions. The calculator should input two numbers and