C Programming Code Examples
C > File Operations Code Examples
C Program to Update Details of Employee using Files
/* C Program to Update Details of Employee using Files */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct emp
{
int empid;
char *name;
};
int count = 0;
void add_rec(char *a);
void display(char *a);
void update_rec(char *a);
void main(int argc, char *argv[])
{
int choice;
while (1)
{
printf("MENU:\n");
printf("1.Add a record\n");
printf("2.Display the file\n");
printf("3.Update the record\n");
printf("Enter your choice:");
scanf("%d", &choice);
switch(choice)
{
case 1:
add_rec(argv[1]);
break;
case 2:
display(argv[1]);
break;
case 3:
update_rec(argv[1]);
break;
case 4:
exit(0);
default:
printf("Wrong choice!!!\nEnter the correct choice\n");
}
}
}
void add_rec(char *a)
{
FILE *fp;
fp = fopen(a, "a+");
struct emp *temp = (struct emp *)malloc(sizeof(struct emp));
temp->name = (char *)malloc(50*sizeof(char));
if (fp == NULL)
printf("Error!!!");
else
{
printf("Enter the employee id\n");
scanf("%d", &temp->empid);
fwrite(&temp->empid, sizeof(int), 1, fp);
printf("enter the employee name\n");
scanf(" %[^\n]s", temp->name);
fwrite(temp->name, 50, 1, fp);
count++;
}
fclose(fp);
free(temp);
free(temp->name);
}
void display(char *a)
{
FILE *fp;
char ch;
int rec = count;
fp = fopen(a, "r");
struct emp *temp = (struct emp *)malloc(sizeof(struct emp));
temp->name = (char *)malloc(50*sizeof(char));
if (fp == NULL)
printf("Error!!");
else
{
while (rec)
{
fread(&temp->empid, sizeof(int), 1, fp);
printf("%d", temp->empid);
fread(temp->name, 50, 1, fp);
printf(" %s\n", temp->name);
rec--;
}
}
fclose(fp);
free(temp);
free(temp->name);
}
void update_rec(char *a)
{
FILE *fp;
char ch, name[5];
int rec, id, c;
fp = fopen(a, "r+");
struct emp *temp = (struct emp *)malloc(sizeof(struct emp));
temp->name = (char *)malloc(50*sizeof(char));
printf("Enter the employee id to update:\n");
scanf("%d", &id);
fseek(fp, 0, 0);
rec = count;
while (rec)
{
fread(&temp->empid, sizeof(int), 1, fp);
printf("%d", temp->empid);
if (id == temp->empid)
{
printf("Enter the employee name to be updated");
scanf(" %[^\n]s", name);
c = fwrite(name, 50, 1, fp);
break;
}
fread(temp->name, 50, 1, fp);
rec--;
}
if (c == 1)
printf("Record updated\n");
else
printf("Update not successful\n");
fclose(fp);
free(temp);
free(temp->name);
}
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.
#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:
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.
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.
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.
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.
Write block of data to stream. Writes an array of count elements, each one with a size of size bytes, from the block of memory pointed by ptr to the current position in the stream. The position indicator of the stream is advanced by the total number of bytes written. Internally, the function interprets the block pointed by ptr as if it was an array of (size*count) elements of type unsigned char, and writes them sequentially to stream as if fputc was called for each byte.
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.
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 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.
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.
The free() function in C library allows you to release or deallocate the memory blocks which are previously allocated by calloc(), malloc() or realloc() functions. It frees up the memory blocks and returns the memory to heap. It helps freeing the memory in your program which will be available for later use. In C, the memory for variables is automatically deallocated at compile time. For dynamic memory allocation in C, you have to deallocate the memory explicitly. If not done, you may encounter out of memory error.
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.
Read block of data from stream. Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr. The position indicator of the stream is advanced by the total amount of bytes read. The total amount of bytes read if successful is (size*count).
The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.
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.
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,
Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. The "malloc" or "memory allocation" method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn't Iniatialize memory at execution time so that it has initializes each block with the default garbage value initially.
C program using Recursion and finds the first 'capital letter' that exists in a string. We have included 'ctype.h' in order to make use of "int isupper(char); " function that's defined inside
C program input decimal number and convert to Hexadecimal number system. The Decimal number system is a base 10 number system. Decimal number system uses 10 symbols to...
C Program Code Decimal point character for nonmonetary values. Thousands separator for nonmonetary values. Specifies grouping for nonmonetary values. Local currency and
A plane figure with 4 sides & 4 right angles & having Equal Opposite sides. Adjucent sides makes an Angle of 90 degree. Just compute the area of a Rectangle if you know its length
How to reverse copy array in C programming language. This program code shall help you learn one of basics of arrays. We shall copy one array into another array but in reverse.