Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes

C Programming Code Examples

C > File Operations Code Examples

Program to Replace a specified Line in a Text File

/* Program to Replace a specified Line in a Text File */ #include <stdio.h> int main(void) { FILE *fileptr1, *fileptr2; char filechar[40]; char c; int delete_line, temp = 1; printf("Enter file name: "); scanf("%s", filechar); fileptr1 = fopen(filechar, "r"); c = getc(fileptr1); //print the contents of file . while (c != EOF) { printf("%c", c); c = getc(fileptr1); } printf(" \n Enter line number to be deleted and replaced"); scanf("%d", &delete_line); //take fileptr1 to start point. rewind(fileptr1); //open replica.c in write mode fileptr2 = fopen("replica.c", "w"); c = getc(fileptr1); while (c != EOF) { if (c == 'n') { temp++; } //till the line to be deleted comes, copy the content to other if (temp != delete_line) { putc(c, fileptr2); } else { while ((c = getc(fileptr1)) != 'n') { } //read and skip the line ask for new text printf("Enter new text"); //flush the input stream fflush(stdin); putc('n', fileptr2); //put 'n' in new file while ((c = getchar()) != 'n') putc(c, fileptr2); //take the data from user and place it in new file fputs("n", fileptr2); temp++; } //continue this till EOF is encountered c = getc(fileptr1); } fclose(fileptr1); fclose(fileptr2); remove(filechar); rename("replica.c", filechar); fileptr1 = fopen(filechar, "r"); //reads the character from file c = getc(fileptr1); //until last character of file is encountered while (c != EOF) { printf("%c", c); //all characters are printed c = getc(fileptr1); } fclose(fileptr1); return 0; }

Get character from stdin. Returns the next character from the standard input (stdin). It is equivalent to calling getc with stdin as argument. A getchar() function is a non-standard function whose meaning is already defined in the stdin.h header file to accept a single input from the user. In other words, it is the C library function that gets a single character (unsigned char) from the stdin. However, the getchar() function is similar to the getc() function, but there is a small difference between the getchar() and getc() function of the C programming language.

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.

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.

Rename file. Changes the name of the file or directory specified by oldname to newname. This is an operation performed directly on a file; No streams are involved in the operation. If oldname and newname specify different paths and this is supported by the system, the file is moved to the new location. If newname names an existing file, the function may either fail or override the existing file, depending on the specific system and library implementation. Proper file access shall be available. The rename() function changes the name of the file specified by oldname to the string referenced by newname. The pointer argument oldname must refer to the name of an existing file. The function returns 0 on success. If rename() fails to rename the file, it returns a nonzero value.

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.

Flush stream. If the given stream was open for writing (or if it was open for updating and the last i/o operation was an output operation) any unwritten data in its output buffer is written to the file. If stream is a null pointer, all such streams are flushed. In all other cases, the behavior depends on the specific library implementation. In some implementations, flushing a stream open for reading causes its input buffer to be cleared (but this is not portable expected behavior).

#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:

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.

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.

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.

Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string. In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.

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,

Remove file. Deletes the file whose name is specified in filename. This is an operation performed directly on a file identified by its filename; No streams are involved in the operation. Proper file access shall be available. The remove() function deletes the file (or directory) referred to by its string argument. To be exact, it "unlinks" the file, or deletes its filename from the file system, so that the file's contents may still exist if the file was linked to more than one name. The remove() function may or may not be able to unlink a file while it is open, depending on the given implementation. The function returns 0 on success. If remove() fails to unlink the file, it returns a nonzero value.

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.

Set position of stream to the beginning. Sets the position indicator associated with stream to the beginning of the file. The end-of-file and error internal indicators associated to the stream are 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 rewind allows to switch between reading and writing.

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.

Write string to stream. Writes the C string pointed by str to the stream. The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This terminating null-character is not copied to the stream. Notice that fputs not only differs from puts in that the destination stream can be specified, but also fputs does not write additional characters, while puts appends a newline character at the end automatically. The fputs() function writes a line of characters into file. It outputs string to a stream. The fputs() function writes a string to the file specified by the FILE pointer argument.

The program takes the range and finds all the 'Prime Numbers' between the range & prints. Lets first take the range of numbers between which you have to find the prime numbers as

Program takes two strings as input & checks whether two strings are anagrams. Take two strings as input and store them in the arrays array1[] array2[] respectively. In the function

This C Program to calculates the volume and surface area of cone. This program is used to find the the volume and surface area of cone. Surface_Area = Pi * r * (r + sqrt(r2 + h2)) and

How to find 'Length of a string' without using in-built library function strlen() in C language. Effective way to find length of string without using strlen() function. In the C every string is

Program search element in a tree recursively. Program searches for a given Node in a Tree. The Tree we have used is the "Binary Search Tree". A Binary search tree follows a concept