C Programming Code Examples
C > Gnu-Linux Code Examples
Copy file using mmap()
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
/* Copy file using mmap() */
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#define PACKAGE "mmap"
int main(int argc, char *argv[]) {
int input, output;
size_t filesize;
void *source, *target;
if(argc != 3)
fprintf(stderr, "%s SOURCE DEST\n"), exit(1);
if((input = open(argv[1], O_RDONLY)) == -1)
fprintf(stderr, "%s: Error: opening file: %s\n", PACKAGE, argv[1]), exit(1);
if((output = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, 0666)) == -1)
fprintf(stderr, "%s: Error: opening file: %s\n", PACKAGE, argv[2]), exit(1);
filesize = lseek(input, 0, SEEK_END);
lseek(output, filesize - 1, SEEK_SET);
write(output, '\0', 1);
if((source = mmap(0, filesize, PROT_READ, MAP_SHARED, input, 0)) == (void *) -1)
fprintf(stderr, "Error mapping input file: %s\n", argv[1]), exit(1);
if((target = mmap(0, filesize, PROT_WRITE, MAP_SHARED, output, 0)) == (void *) -1)
fprintf(stderr, "Error mapping ouput file: %s\n", argv[2]), exit(1);
memcpy(target, source, filesize);
munmap(source, filesize);
munmap(target, filesize);
close(input);
close(output);
return 0;
}
fprintf() Function in C
Write formatted data to stream. Writes the C string pointed by format to the stream. 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.
After the format parameter, the function expects at least as many additional arguments as specified by format.
Syntax for fprintf() Function in C
#include <stdio.h>
int fprintf ( FILE * stream, const char * format, ... );
stream
Pointer to a FILE object that identifies an output stream.
format
C string that contains the text to be written to the stream. 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:
%[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.
h
The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).
l
The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.
L
The argument is interpreted as a long double (only applies to floating point specifiers - e, E, f, g and G).
... (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.
On success, the total number of characters written is returned.
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
26
/* write the C string pointed by format to the stream by fprintf() function example */
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
mmap() Function in C
The mmap() function establishes a mapping between a process' address space and a stream file. The address space of the process from the address returned to the caller, for a length of len, is mapped onto a stream file starting at offset off. The portion of the stream file being mapped is from starting offset off for a length of len bytes. The actual address returned from the function is derived from the values of flags and the value specified for address.
The mmap() function causes a reference to be associated with the file represented by fildes. This reference is not removed by subsequent close operations. The file remains referenced as long as a mapping exists over the file.
If a mapping already exists for the portion of the processes address space that is to be mapped and the value MAP_FIXED was specified for flags, then the previous mappings for the affected pages are implicitly unmapped. If one or more files affected by the implicit unmap no longer have active mappings, these files will be unreferenced as a result of mmap().
The use of the mmap() function is restricted by the QSHRMEMCTL System Value. When this system value is 0, the mmap() function may not create a shared mapping having with PROT_WRITE capability. Essentially, this prevents the creation of a memory map that could alter the contents of the stream file being mapped. If the flags parameter indicated MAP_SHARED, the prot parameter specifies PROT_WRITE and the QSHRMEMCTL system value is 0, then the mmap() functions will fail and an error number of EACCES results.
When the mmap() function creates a memory map, the current value of the QSHRMEMCTL system value is stored with the mapping. This further restricts attempts to change the protection of the mapping through the use of the mprotect function. Changing the system valueonly affects memory maps created after the system value is changed.
If the size of the file increases after the mmap() function completes, then the whole pages beyond the original end of file will not be accessible via the mapping.
If the size of the mapped file is decreased after mmap(), attempts to reference beyond the end of the file are undefined and may result in an MCH0601 exception.
Any data written to that portion of the file that is allocated beyond end-of-file may not be preserved. Changes made beyond end of file via mapped access may not be preserved.
The portion of the file beyond end-of-file is assumed to be zero by the traditional file access APIs such as read(), readv(), write(), writev(), and ftruncate(). The system may clear a partial page, or whole pages allocated beyond end-of-file. This must be taken into account when directly changing a memory mapped file beyond end-of-file. It is not recommended that data be directly changed beyond end-of-file because the extra space allocated varies and unpredictable results may occur.
The mmap() function is only supported for *TYPE2 stream files (*STMF) existing in the "root" (/), QOpenSys, and user-defined file systems.
Journaling cannot be started while a file is memory mapped. Likewise, a journaled file cannot be memory mapped. The mmap() function will fail with ENOTSUP if the file is journaled.
The off parameter must be zero or a multiple of the system page size. The _SC_PAGESIZE or _SC_PAGE_SIZE options on the sysconf() function may be used to retrieve the system page size.
Syntax for mmap() Function in C
#include <sys/mman.h>
void *mmap( void *addr, size_t len, int protection, int flags, int fildes, off_t off);
addr
(Input) The starting address of the memory area to be mapped. If the MAP_FIXED value is specified with the flag parameter, then address must be a multiple of the system page size. Use the _SC_PAGESIZE or _SC_PAGE_SIZE options of the sysconf() API to obtain the actual page size in an implementation-independent manner. When the MAP_FIXED flag is specified, this address must not be zero.
len
(Input) The length in bytes to map. A length of zero will result in an errno of EINVAL.
protection
(Input) The access allowed to this process for this mapping. Specify PROT_NONE, PROT_READ, PROT_WRITE, or a the inclusive-or of PROT_READ and PROT_WRITE. You cannot specify a protection value more permissive than the mode in which the file was opened.
The PROT_WRITE value requires that the file be opened for write and read access.
The following table shows the symbolic constants allowed for the protection parameter.
PROT_READ 1 Read access is allowed.
PROT_WRITE 2 Write access is allowed. Note that this value assumes PROT_READ also.
PROT_NONE 8 No data access is allowed.
PROT_EXEC 4 This value is allowed, but is equivalent to PROT_READ.
flags
(Input) Further defines the type of mapping desired. There are actually two independent options controlled through the flags parameter.
The first attribute controls whether or not changes made through the mapping will be seen by other processes. The MAP_PRIVATE option will cause a copy on write mapping to be created. A change to the mapping results in a change to a private copy of the affected portion of the file. These changes cannot be seen by other processes. The MAP_SHARED option provides a memory mapping of the file where changes (if allowed by the protection parameter) are made to the file. Changes are shared with other processes when MAP_SHARED is specified.
The second control provided by the flags parameter in conjunction with the value of the addr parameter influences the address range assigned to the mapping. You may request one of the following address selection modes:
• An exact address range specification. The system will set up the mapping at this location if the address range is valid. Any mapping in the successfully mapping range that existed prior to the mapping operation is implicitly unmapped by this operation.
• A suggested address range. The system will select a range close to the suggested range.
• System selected. The system will select an address range. This usually is used to acquire the initial memory map range. Subsequent ranges can be mapped relative to this range.
The MAP_FIXED flag value specifies that the virtual address has been specified through the addr parameter. The mmap() function will use the value of addr as the starting point of the memory map.
When MAP_FIXED is set in the flags parameter, the system is informed that the return value must be equal to the value of addr. An invalid value of addr when MAP_FIXED is specified will result in a value of MAP_FAILED, which has a value of 0, for the returned value and the the value of errno will be set to EINVAL.
When MAP_FIXED is not specified, a value of zero for parameter addr indicates that the system may choose the value for the return value. If MAP_FIXED is not specified and a nonzero value is specified for addr, the system will take this as a suggestion to find a contiguous address range close to the specified address.
The following table shows the symbolic constants allowed for the flags parameter.
MAP_SHARED 4 Changes are shared.
MAP_PRIVATE 2 Changes are private.
MAP_FIXED 1 Parameter addr has exact address
fildes
(Input) An open file descriptor.
off
(Input) The offset into the file, in bytes, where the map should begin.
No authority checking is performed by the mmap() function because this was done by the open() functions which assigned the file descriptor, fildes, used by the mmap() function.
The following table shows the open access intent that is required for the various combinations of the mapping sharing mode and mapping intent.
MAP_SHARED PROT_READ O_RDONLY or O_RDWR
MAP_SHARED PROT_WRITE O_RDWR
MAP_SHARED PROT_NONE O_RDONLY or O_RDWR
MAP_PRIVATE PROT_READ O_RDONLY or O_RDWR
MAP_PRIVATE PROT_WRITE O_RDONLY or O_RDWR
MAP_PRIVATE PROT_NONE O_RDONLY or O_RDWR
Upon successful completion, the mmap() function returns the address at which the mapping was placed; otherwise, it returns a value of MAP_FAILED, which has a value of 0, and sets errno to indicate the error. The symbol MAP_FAILED is defined in the header 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
/* map pages of memory by mmap() function code example */
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
int main(void) {
size_t pagesize = getpagesize();
printf("System page size: %zu bytes\n", pagesize);
char * region = mmap(
(void*) (pagesize * (1 << 20)), // Map from the start of the 2^20th page
pagesize, // for one page length
PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_ANON|MAP_PRIVATE, // to a private block of hardware memory
0,
0
);
if (region == MAP_FAILED) {
perror("Could not mmap");
return 1;
}
strcpy(region, "Hello, honey");
printf("Contents of region: %s\n", region);
int unmap_result = munmap(region, 1 << 10);
if (unmap_result != 0) {
perror("Could not munmap");
return 1;
}
// getpagesize
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;
}
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;
}
munmap() Function in C
The munmap() function shall remove any mappings for those entire pages containing any part of the address space of the process starting at addr and continuing for len bytes. Further references to these pages shall result in the generation of a SIGSEGV signal to the process. If there are no mappings in the specified address range, then munmap() has no effect.
Syntax for munmap() Function in C
#include <sys/mman.h>
int munmap(void *addr, size_t len);
addr
The beginning of the range of addresses that you want to unmap.
len
The length of the range of addresses, in bytes.
Upon successful completion, munmap() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.
The implementation shall require that addr be a multiple of the page size {PAGESIZE}.
If a mapping to be removed was private, any modifications made in this address range shall be discarded.
Any memory locks (see mlock() and mlockall() ) associated with this address range shall be removed, as if by an appropriate call to munlock().
If a mapping removed from a typed memory object causes the corresponding address range of the memory pool to be inaccessible by any process in the system except through allocatable mappings (that is, mappings of typed memory objects opened with the POSIX_TYPED_MEM_MAP_ALLOCATABLE flag), then that range of the memory pool shall become deallocated and may become available to satisfy future typed memory allocation requests.
A mapping removed from a typed memory object opened with the POSIX_TYPED_MEM_MAP_ALLOCATABLE flag shall not affect in any way the availability of that typed memory for allocation.
The behavior of this function is unspecified if the mapping was not established by a call to mmap().
The munmap() function shall fail if:
EINVAL
Addresses in the range [addr,addr+len) are outside the valid range for the address space of a process.
EINTR
The call was interrupted by a signal.
ENOMEM
The memory manager fails to allocate memory to handle a user's munmap() request. This allocation of memory is necessary for internal structures to represent the new state of mapped memory.
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
/* remove memory mapping by munmap() function code example */
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
main() {
char fn[]="creat.file";
char text[]="This is a test";
int fd;
int PageSize;
if ((fd =
open(fn, O_CREAT | O_RDWR | O_APPEND,S_IRWXU) < 0)
perror("open() error");
else if (write(fd, text, strlen(text)) < 0;
error("write() error=");
else if ( (PageSize=sysconf(_SC_PAGESIZE)) < 0 )
error("sysconf() Error=");
else {
off_t lastoffset = lseek( fd, PageSize-1, SEEK_SET);
write(fd, " ", 1); /* grow file to 1 page. */
/* mmap the file. */
void *address;
int len;
my_offset = 0;
len = 4096; /* Map one page */
address =
mmap(NULL, len, PROT_READ, MAP_SHARED, fd, my_offset)
if ( address != MAP_FAILED ) {
if ( munmap( address, len ) ) == -1) {
error("munmap failed with error:");
}
}
close(fd);
unlink(fn);
}
}
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;
}
memcpy() Function in C
Copy block of memory. Copies the values of num bytes from the location pointed to by source directly to the memory block pointed to by destination. The underlying type of the objects pointed to by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data.
The function does not check for any terminating null character in source - it always copies exactly num bytes.
To avoid overflows, the size of the arrays pointed to by both the destination and source parameters, shall be at least num bytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach).
Syntax for memcpy() Function in C
#include <string.h>
void * memcpy ( void * destination, const void * source, size_t num );
destination
Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
source
Pointer to the source of data to be copied, type-casted to a pointer of type const void*.
num
Number of bytes to copy. size_t is an unsigned integral type.
This function returns a pointer to destination.
The memcpy() function does not check for the overflow of the receiving memory area.
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
/* copy block of memory by memcpy() function code example */
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[])
{
/* Create a place to store our results */
int result;
/* Create two arrays to hold our data */
char original[50];
char newcopy[50];
/* Copy a string into the original array */
strcpy(original, "C memcpy function");
/* Copy the first 24 characters of the original
array into the newcopy array */
result = memcpy(newcopy, original, 24);
/* Set the character at position 24 to a null (char 0)
in the newcopy array to ensure the string is terminated
(This is important since memcpy does not initialize memory
and printf expects a null at the end of a string) */
newcopy[24] = 0;
/* Display the contents of the new copy */
printf("%s\n", newcopy);
return 0;
}
lseek() Function in C
Change the offset of a file. Changes the current file offset to a new position in a z/OS® UNIX file. The new position is the given byte offset from the position specified by pos. After you have used lseek() to seek to a new location, the next I/O operation on the file begins at that location.
lseek() lets you specify new file offsets past the current end of the file. If data is written at such a point, read operations in the gap between this data and the old end of the file will return bytes containing zeros. (In other words, the gap is assumed to be filled with zeros.)
Seeking past the end of a file, however, does not automatically extend the length of the file. There must be a write operation before the file is actually extended. Special behavior for POSIX C: For character special files, lseek() sets the file offset to the specified value. z/OS UNIX services ignore the file offset value during the read/write processing to character special files.
Syntax for lseek() Function in C
#include <unistd.h>
off_t lseek(int fildes, off_t offset, int pos);
fildes
The file whose current file offset you want to change.
offset
The amount (positive or negative) the byte offset is to be changed. The sign indicates whether the offset is to be moved forward (positive) or backward (negative).
pos
One of the following symbols (defined in the unistd.h header file):
SEEK_SET The start of the file
SEEK_CUR The current file offset in the file
SEEK_END The end of the file
Large file support for z/OS UNIX files: Large z/OS UNIX files are supported automatically for AMODE 64 C/C++ applications. AMODE 31 C/C++ applications must be compiled with the option LANGLVL(LONGLONG) and define the _LARGE_FILES feature test macro before any headers are included to enable this function to operate on z/OS UNIX files that are larger than 2 GB in size. File size and offset fields are enlarged to 63 bits in width. Therefore, any other function operating on the file is required to define the _LARGE_FILES feature test macro as well.
If successful, lseek() returns the new file offset, measured in bytes from the beginning of the file.
If unsuccessful, lseek() returns -1 and sets errno to one of the following values:
EBADF
fildes is not a valid open file descriptor.
EINVAL
pos contained something other than one of the three options, or the combination of the pos values would have placed the file offset before the beginning of the file.
EOVERFLOW
The resulting file offset would be a value which cannot be represented correctly in an object of type off_t.
ESPIPE
fildes is associated with a pipe or FIFO special file.
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
/* move the read/write file offset by lseek() function code example */
// C program to read nth byte of a file and
// copy it to another file using lseek
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
void func(char arr[], int n)
{
// Open the file for READ only.
int f_write = open("start.txt", O_RDONLY);
// Open the file for WRITE and READ only.
int f_read = open("end.txt", O_WRONLY);
int count = 0;
while (read(f_write, arr, 1))
{
// to write the 1st byte of the input file in
// the output file
if (count < n)
{
// SEEK_CUR specifies that
// the offset provided is relative to the
// current file position
lseek (f_write, n, SEEK_CUR);
write (f_read, arr, 1);
count = n;
}
// After the nth byte (now taking the alternate
// nth byte)
else
{
count = (2*n);
lseek(f_write, count, SEEK_CUR);
write(f_read, arr, 1);
}
}
close(f_write);
close(f_read);
}
// Driver code
int main()
{
char arr[100];
int n;
n = 5;
// Calling for the function
func(arr, n);
return 0;
}
write() Function in C
Write to a file descriptor. write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd. The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the RLIMIT_FSIZE resource limit is encountered, or the call was interrupted by a signal handler after having written less than count bytes.
For a seekable file (i.e., one to which lseek may be applied, for example, a regular file) writing takes place at the current file offset, and the file offset is incremented by the number of bytes actually written. If the file was opened with O_APPEND, the file offset is first set to the end of the file before writing. The adjustment of the file offset and the write operation are performed as an atomic step.
Syntax for write() Function in C
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
fd
It is the file descriptor which has been obtained from the call to open. It is an integer value. The values 0, 1, 2 can also be given, for standard input, standard output & standard error, respectively .
buf
It points to a character array, which can be used to store content obtained from the file pointed to by fd.
count
It specifies the number of bytes to be written from the file into the character array.
POSIX requires that a read which can be proved to occur after a write() has returned returns the new data. Note that not all file systems are POSIX conforming.
On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately.
If count is zero and fd refers to a regular file, then write() may return a failure status if one of the errors below is detected. If no errors are detected, 0 will be returned without causing any other effect. If count is zero and fd refers to a file other than a regular file, the results are not specified.
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
/* write to a file descriptor by write() function code example */
// C program to illustrate
// I/O system Calls
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
int main (void)
{
int fd[2];
char buf1[12] = "hello world";
char buf2[12];
// assume foobar.txt is already created
fd[0] = open("foobar.txt", O_RDWR);
fd[1] = open("foobar.txt", O_RDWR);
write(fd[0], buf1, strlen(buf1));
write(1, buf2, read(fd[1], buf2, 12));
close(fd[0]);
close(fd[1]);
return 0;
}
#define Directive in C
In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.
Syntax for #define Directive in C
#define NAME value /* this syntax creates a constant using define*/
// Or
#define NAME (expression) /* this syntax creates a constant using define*/
NAME
is the name of a particular constant. It can either be defined in smaller case or upper case or both. Most of the developers prefer the constant names to be in the upper case to find the differences.
value
defines the value of the constant.
Expression
is the value that is assigned to that constant which is defined. The expression should always be enclosed within the brackets if it has any operators.
In the C programming language, the preprocessor directive acts an important role within which the #define directive is present that is used to define the constant or the micro substitution.
The #define directive can use any of the basic data types present in the C standard. The #define preprocessor directive lets a programmer or a developer define the macros within the source code.
This macro definition will allow the constant value that should be declared for the usage. Macro definitions cannot be changed within the program's code as one does with other variables, as macros are not variables.
The #define is usually used in syntax that created a constant that is used to represent numbers, strings, or other expressions.
The #define directive should not be enclosed with the semicolon(;). It is a common mistake done, and one should always treat this directive as any other header file. Enclosing it with a semicolon will generate an error.
The #define creates a macro, which is in association with an identifier or is parameterized identifier along with a token string. After the macro is defined, then the compiler can substitute the token string for each occurrence of the identifier within the source file.
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
/* #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. */
#include <stdio.h>
#include <string.h>
typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;
int main( ) {
Book book;
strcpy( book.title, "C Programming");
strcpy( book.author, "XCoder");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
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;
}
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;
}
#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;
}
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;
}
This C Program implements a Selection Sort. 'Selection Sort' works by finding the smallest unsorted item in the list and swapping it with the item in the current position. It is used for
A magic square is a simple mathematical game developed during the 1500. Square is divided into equal number of rows and columns. Start filling each square with the
Search an element in the linked list without using Recursion. C Program, using iteration, Searches for an Element in a Linked List. A Linked List is ordered set of Data Elements,
C Program code to find area & circumference of circle. In this program we have to calculate the area and circumference of the circle. Two formulas for finding Circumference and Area