C Programming Code Examples
C > File Operations Code Examples
C program to Copy the contents of one file into another using fputc
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
/* C program to Copy the contents of one file into another using fputc */
#include<stdio.h>
#include<process.h>
void main() {
FILE *fp1, *fp2;
char a;
clrscr();
fp1 = fopen("test.txt", "r");
if (fp1 == NULL) {
puts("cannot open this file");
exit(1);
}
fp2 = fopen("test1.txt", "w");
if (fp2 == NULL) {
puts("Not able to open this file");
fclose(fp1);
exit(1);
}
do {
a = fgetc(fp1);
fputc(a, fp2);
} while (a != EOF);
fcloseall();
getch();
}
#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"
#include <header_file>
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;
}
exit() Function in C
The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program. The exit() function is the standard library function of the C, which is defined in the stdlib.h header file. So, we can say it is the function that forcefully terminates the current program and transfers the control to the operating system to exit the program. The exit(0) function determines the program terminates without any error message, and then the exit(1) function determines the program forcefully terminates the execution process.
Syntax for exit() Function in C
#include <stdlib.h>
void exit(int status)
status
Status code. If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure.
The exit function does not return anything.
• We must include the stdlib.h header file while using the exit () function.
• It is used to terminate the normal execution of the program while encountered the exit () function.
• The exit () function calls the registered atexit() function in the reverse order of their registration.
• We can use the exit() function to flush or clean all open stream data like read or write with unwritten buffered data.
• It closed all opened files linked with a parent or another function or file and can remove all files created by the tmpfile function.
• The program's behaviour is undefined if the user calls the exit function more than one time or calls the exit and quick_exit function.
• The exit function is categorized into two parts: exit(0) and exit(1).
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
/* call all functions registered with atexit and terminates the program by exit() function example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
// declaration of the variables
int i, num;
printf ( " Enter the last number: ");
scanf ( " %d", &num);
for ( i = 1; i<num; i++)
{
// use if statement to check the condition
if ( i == 6 )
/* use exit () statement with passing 0 argument to show termination of the program without any error message. */
exit(0);
else
printf (" \n Number is %d", i);
}
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;
}
fcloseall() Function in C
Close all open stream files. The fcloseall() function closes all open streams, including stdin, stdout, and stderr. This includes streams created (and not yet closed) by fdopen(), fopen(), and freopen(). This function causes all open streams of the process to be closed and the connections to corresponding files to be broken. All buffered data is written and any buffered input is discarded.
The fcloseall function returns a value of 0 if all the files were closed successfully, and EOF if an error was detected. This function should be used only in special situations, e.g., when an error occurred and the program must be aborted. Normally each single stream should be closed separately so that problems with individual streams can be identified. It is also problematic since the standard streams will also be closed. The function fcloseall is declared in stdio.h.
Syntax for fcloseall() Function in C
#include <stdio.h>
int fcloseall( void );
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
/* close all open streams, including stdin, stdout, and stderr by fcloseall() function code example */
void main()
{
FILE *fp1,*fp2;
char a;
clrscr();
fp1=fopen("d:\\dtp\\test.txt","r");
if(fp1==NULL)
{
puts("cannot open this file");
exit(1);
}
fp2=fopen("d:\\dtp\\test1.txt","w");
if(fp2==NULL)
{
puts("Not able to open this file");
fclose(fp1);
exit(1);
}
do
{
a=fgetc(fp1);
a=toupper(a);
fputc(a,fp2);
}
while(a!=EOF);
fcloseall();
getch();
}
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;
}
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;
}
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
}
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;
}
getch() Function in C
The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program.
Syntax for getch() Function in C
#include <conio.h>
int getch(void);
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
/* wait for any character input from keyboard by getch() function example. */
// C code to illustrate working of
// getch() to accept hidden inputs
#include <conio.h>
#include <dos.h> // delay()
#include <stdio.h>
#include <string.h>
void main()
{
// Taking the password of 8 characters
char pwd[9];
int i;
// To clear the screen
clrscr();
printf("Enter Password: ");
for (i = 0; i < 8; i++) {
// Get the hidden input
// using getch() method
pwd[i] = getch();
// Print * to show that
// a character is entered
printf("*");
}
pwd[i] = '\0';
printf("\n");
// Now the hidden input is stored in pwd[]
// So any operation can be done on it
// Here we are just printing
printf("Entered password: ");
for (i = 0; pwd[i] != '\0'; i++)
printf("%c", pwd[i]);
// Now the console will wait
// for a key to be pressed
getch();
}
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;
}
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;
}
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;
}
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;
}
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;
}
clrscr() Function in C
Function clrscr() clears the screen and moves the cursor to the upper left-hand corner of the screen. If you are using the GCC compiler, use system function to execute the clear/cls command. clrscr() function is also a non-standard function defined in "conio.h" header. This function is used to clear the console screen. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.
Syntax to Clear the Console in C
#include<conio.h>
clrscr();
OR
system("cls");
OR
system("clear");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* clear the screen and moves the cursor to the upper left-hand corner of the screen by clrscr() function example. */
#include <stdio.h>
// clrscr() function definition
void clrscr(void)
{
system("clear");
}
int main()
{
clrscr(); //clear output screen
printf("Hello World!!!"); //print message
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 */
};
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;
}
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
}
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;
}
Lets find the length of the string using library function strlen(). A "string" is charracter array and a "Character Array" have character range between 0 to length-1. Thus we have position
C Program using Pointers to Read in an array of integers and Print its elements in Reverse order. We have declared one pointer variable and one array and address of first element of
Get memory in c programming language. Generate 10 random numbers. Write the entire array in one step. Free memory. Get memory again. Read the entire array in one