C Programming Code Examples
C > File Operations Code Examples
C Program to Convert the Content of File to UpperCase
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/* C Program to Convert the Content of File to UpperCase */
#include <stdio.h>
int to_upper_file(FILE *);
int main(int argc,char *argv[])
{
FILE *fp;
int status;
if (argc == 1)
{
printf("Insufficient Arguments:");
printf("No File name is provided at command line");
return;
}
if (argc > 1)
{
fp = fopen(argv[1],"r+");
status = to_upper_file(fp);
/* If the status returned is 0 then the coversion of file content was completed successfully */
if (status == 0)
{
printf("\n The content of \"%s\" file was successfully converted to upper case\n",argv[1]);
return;
}
/* If the status returnes is -1 then the conversion of file content was not done */
if (status == -1)
{
printf("\n Failed to convert");
return;
}
}
}
/* convert the file content to uppercase */
int to_upper_file(FILE *fp)
{
char ch;
if (fp == NULL)
{
perror("Unable to open file");
return -1;
}
else
{
/* Read the file content and convert to uppercase */
while (ch != EOF)
{
ch = fgetc(fp);
if ((ch >= 'a') && (ch <= 'z'))
{
ch = ch - 32;
fseek(fp,-1,SEEK_CUR);
fputc(ch,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;
}
#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;
}
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;
}
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;
}
fseek() Function in C
Reposition stream position indicator. Sets the position indicator associated with the stream to a new position. For streams open in binary mode, the new position is defined by adding offset to a reference position specified by origin.
For streams open in text mode, offset shall either be zero or a value returned by a previous call to ftell, and origin shall necessarily be SEEK_SET.
If the function is called with other values for these arguments, support depends on the particular system and library implementation (non-portable).
The end-of-file internal indicator of the stream is cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.
On streams open for update (read+write), a call to fseek allows to switch between reading and writing.
The fseek() function is used to move the cursor in the file to the desired position.
Syntax for fseek() Function in C
#include <stdio.h>
int fseek ( FILE * stream, long int offset, int origin );
stream
Pointer to a FILE object that identifies the stream.
offset
Binary files: Number of bytes to offset from origin. Text files: Either zero, or a value returned by ftell.
origin
Position used as reference for the offset. It is specified by one of the following constants defined in SEEK_SET
Beginning of file
SEEK_CUR
Current position of the file pointer
SEEK_END
End of file *
* Library implementations are allowed to not meaningfully support SEEK_END (therefore, code using it has no real standard portability).
If successful, the function returns zero.
Otherwise, it returns non-zero value.
If a read or write error occurs, 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
/* set the position indicator associated with the stream by fseek() function code example */
#include <stdio.h>
int main()
{
FILE *fx;
fx = fopen("new_file.txt", "r");
//Using the fseek function to move the file pointer to the end
fseek(fx, 0, SEEK_END);
// Using the file function in order to Print the position of file pointer
printf("Position of file pointer is : ");
printf("%ld \n", ftell(fx));
// Using the file function 'fseek' to move the file position 10 characters ahead
fseek(fx,10,SEEK_SET);
int ch;
// printing the resulting file after 10 characters
printf("Resulting bytes after the 10 characters in a file are: ");
while( (ch=fgetc(fx)) != EOF)
// using function 'putchar(x)'' to print the file characters on console
putchar(ch);
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;
}
printf() Function in C
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.
printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers, but are sufficient for many purposes.
Syntax for printf() function in C
#include <stdio.h>
int printf ( const char * format, ... );
format
C string that contains the text to be written to stdout.
It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.
A format specifier follows this prototype: [see compatibility note below]
%[flags][width][.precision][length]specifier
Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
specifier
a conversion format specifier.
d or i
Signed decimal integer
u
Unsigned decimal integer
o
Unsigned octal
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (uppercase)
f
Decimal floating point, lowercase
F
Decimal floating point, uppercase
e
Scientific notation (mantissa/exponent), lowercase
E
Scientific notation (mantissa/exponent), uppercase
g
Use the shortest representation: %e or %f
G
Use the shortest representation: %E or %F
a
Hexadecimal floating point, lowercase
A
Hexadecimal floating point, uppercase
c
Character
s
String of characters
p
Pointer address
n
Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location.
%
A % followed by another % character will write a single % to the stream.
The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
flags
one or more flags that modifies the conversion behavior (optional)
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
width
an optional * or integer value used to specify minimum width field.
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.precision
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
.number
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
For g and G specifiers: This is the maximum number of significant digits to be printed.
For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
length
an optional length modifier that specifies the size of the argument.
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.
If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.
If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number 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
/* print formatted data to stdout by printf() function example */
#include <stdio.h>
int main()
{
char ch;
char str[100];
int a;
float b;
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
printf("Enter integer and then a float: ");
// Taking multiple inputs
scanf("%d%f", &a, &b);
printf("You entered %d and %f", a, b);
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;
}
perror() Function in C
Print error message. Interprets the value of errno as an error message, and prints it to stderr (the standard error output stream, usually the console), optionally preceding it with the custom message specified in str.
errno is an integral variable whose value describes the error condition or diagnostic information produced by a call to a library function (any function of the C standard library may set a value for errno, even if not explicitly specified in this reference, and even if no error happened), see errno for more info.
Syntax for perror() Function in C
#include <stdio.h>
void perror ( const char * str );
str
C string containing a custom message to be printed before the error message itself. If it is a null pointer, no preceding custom message is printed, but the error message is still printed. By convention, the name of the application itself is generally used as parameter.
This function does not return any value.
The error message produced by perror is platform-depend.
If the parameter str is not a null pointer, str is printed followed by a colon (:) and a space. Then, whether str was a null pointer or not, the generated error description is printed followed by a newline character ('\n').
perror should be called right after the error was produced, otherwise it can be overwritten by calls to other functions.
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
/* print an error message corresponding to the value of errno with perror() function code example */
/* error handling with perror() function and errno */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
main()
{
FILE *fp;
char filename[80];
printf("Enter filename: ");
gets(filename);
if (( fp = fopen(filename, "r")) == NULL)
{
perror("You goofed!");
printf("errno = %d.\n", errno);
exit(1);
}
else
{
puts("File opened for reading.");
fclose(fp);
}
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;
}
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;
}
Logical Operators in C
An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. These operators are used to perform logical operations and used with conditional statements like C if-else statements.
&&
Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
||
Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.
!
Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.
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
/* logical operators in C language */
#include <stdio.h>
main() {
int a = 4;
int b = 23;
int c ;
if ( a && b ) {
printf("Line 1 - Condition is true\n" );
}
if ( a || b ) {
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 2;
b = 8;
if ( a && b ) {
printf("Line 3 - Condition is true\n" );
} else {
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) ) {
printf("Line 4 - Condition is true\n" );
}
}
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;
}
If Else If Ladder in C/C++
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements.
In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax of if...else Ladder in C
if (Condition1)
{ Statement1; }
else if(Condition2)
{ Statement2; }
.
.
.
else if(ConditionN)
{ StatementN; }
else
{ Default_Statement; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* write a C program which demonstrate use of if-else-if ladder statement */
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter a Number: ");
scanf("%d",&a);
if(a > 0)
{
printf("Given Number is Positive");
}
else if(a == 0)
{
printf("Given Number is Zero");
}
else if(a < 0)
{
printf("Given Number is Negative");
}
getch();
}
Reads a number of objects by size and stores them in buf. C programming code returns the number of items actually read. Get open a file and read. If there is an error give a message.
A 'Palindrome' is a special string which reads same from backward or forward such as eye, mom, madam, dad, bob, teet. We traverse a string character by character 'both direction'
Find the "Length of str1". Increment count till we reach the Terminating character. Find the "Length of str2". Check that we have enough 'space' for both strings. Copy 2. string to end
C Program to input two angles from user and find third angle of the triangle. How to find all angles of a triangle if two angles are given by user using C programming. Sum of angles of