C Programming Code Examples
C > File Operations Code Examples
C Program to Join Lines of Two given Files and Store them in a New 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/* C Program to Join Lines of Two given Files and Store them in a New file */
#include <stdio.h>
#include <stdlib.h>
/* Function Prototype */
int joinfiles(FILE *, FILE *, FILE *);
char ch;
int flag;
void main(int argc, char *argv[])
{
FILE *file1, *file2, *target;
file1 = fopen(argv[1], "r");
if (file1 == NULL)
{
perror("Error Occured!");
}
file2 = fopen(argv[2], "r");
if (file2 == NULL)
{
perror("Error Occured!");
}
target = fopen(argv[3], "a");
if (target == NULL)
{
perror("Error Occured!");
}
joinfiles(file1, file2, target); /* Calling Function */
if (flag == 1)
{
printf("The files have been successfully concatenated\n");
}
}
/* Code join the two given files line by line into a new file */
int joinfiles(FILE *file1, FILE *file2, FILE *target)
{
while ((fgetc(file1) != EOF) || (fgetc(file2) != EOF))
{
fseek(file1, -1, 1);
while ((ch = fgetc(file1)) != '\n')
{
if (ch == EOF)
{
break;
}
else
{
fputc(ch, target);
}
}
while ((ch = fgetc(file2)) != '\n')
{
if (ch == EOF)
{
break;
}
else
{
fputc(ch, target);
}
}
fputc('\n', target);
}
fclose(file1);
fclose(file2);
fclose(target);
return flag = 1;
}
The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.
Close file. Closes the file associated with the stream and disassociates it. All internal buffers associated with the stream are disassociated from it and flushed: the content of any unwritten output buffer is written and the content of any unread input buffer is discarded. Even if the call fails, the stream passed as parameter will no longer be associated with the file nor its buffers.
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.
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.
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.
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.
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.
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
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.
#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:
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,
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.
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.
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.
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. 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.
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.
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.
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.
Adding two numbers using inline assembly language. Assembly language can be written in c. C supports assembly as well as higher language features so called "middle level...
Finding the first digit of any number is little expensive than last digit. To find first digit of a number we divide the given number by 10 until number is greater than 10. At the end...
C Language program is used to Find the Sum of the geometric progression series. Here G.P stands for geometric progression. Geometric progression, or GP, is a sequence where each
C Programming to assignment operators. An Assignment Operator is used for assigning a value to a variable. C code demonstrate the working of assignment operators. The most
C Language code how to display a table in C programming language is more or less similar to that of counting. We use only one iteration and increment it with value of which table is