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

Messing about with formatted file I/O

/* Messing about with formatted file I/O */ #include <stdio.h> int main() { long number1 = 2888637L; long number2 = 3256223L; long number3 = 78477834L; long number4 = 0L; long number5 = 0L; long number6 = 0L; float fnum = 0.0f; int ival[6] = { 0 }; int j = 0; FILE *pfile = NULL; char *filename = "C:\\myfile.txt"; pfile = fopen(filename, "w"); if(pfile == NULL){ printf("Error opening %s for writing. Program terminated.", filename); } fprintf(pfile, "%6ld%6ld%6ld", number1, number2, number3); fclose(pfile); pfile = fopen(filename, "r"); fscanf(pfile, "%6ld%6ld%6ld", &number4, &number5 ,&number6); printf("\n %6ld %6ld %6ld", number4, number5, number6); rewind(pfile); /* Go to the beginning of the file */ fscanf(pfile, "%2d%3d%3d%3d%2d%2d%3f", &ival[0], &ival[1],&ival[2], &ival[3], &ival[4] , &ival[5], &fnum); fclose(pfile); remove(filename); for( j = 0 ; j < 6 ; j++ ) printf("%d\n", ival[j]); printf("\nfnum = %f\n", fnum); }

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.

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.

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.

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.

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.

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.

The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.

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

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.

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.

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.

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,

Read formatted data from stream. Reads data from the stream 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.






Program to Fibonacci Series. Fibonacci Series generates subsequent number by adding two previous numbers and Fibonacci Series starts from 2 numbers F0 & F1. The initial values of



Returns the time as a string in 12 or 24 hour format. Stores the time as a string. Getting time value. Getting time and date structure. Save the hour value. Adjust if 12 hour format.

C program code asking the character from user to enter. Returns nonzero if character is a printable character, including a space; otherwise zero is returned. It's printable char.

Input week day number from user. Store it in a variable say week. Print Monday if week=1. I have assumed Monday as first day of week. And check condition for all 7 days & print the

As we know that the one "Dimensional Array" name works as a pointer to the base element of the Array. However in the case "2D Arrays" the logic is slightly different. You can consider