User defined functions in C
C User-defined functions
User-defined functions in C are functions that are created by the user to perform a specific task. These functions can be called from anywhere within the program, just like built-in functions. In C, you can define your own functions to perform specific tasks.
C functions
- Function definitions can be placed anywhere in a C program, but it is common to define all functions at the beginning of the program before the
main
function. This allows the program to use the functions before they are defined. - To perform input and output operations on a file in C, you will need to use the file handling functions provided by the standard library. Here is an example program that demonstrates how to open a file for reading, read the contents of the file, and then close the file:
#include <stdio.h>
int main() { // Declare a file pointer FILE *fp; // Open the file for reading fp = fopen("input.txt", "r"); // Check if the file was successfully opened if (fp == NULL) { printf("Error opening file\n"); return 1; } // Declare a character array to store the contents of the file char buffer[100]; // Read the contents of the file into the buffer fgets(buffer, 100, fp); // Print the contents of the buffer printf("%s", buffer); // Close the file fclose(fp); return 0; }
Output
Error opening file
User-Defined Functions
This program will open the file input.txt
for reading, read the first 100 characters from the file into the buffer
array, and then print the contents of the buffer
array to the console.
To write to a file in C, you can use the fputs
function. Here is an example program that demonstrates how to open a file for writing, write some text to the file, and then close the file:
#include <stdio.h> int addNumbers (int x, int y); // function prototype int main () { int l1, l2, sum; printf ("Enters two numbers: "); scanf ("%d %d", &l1, &l2); sum = addNumbers (l1, l2); // function call printf ("sum = %d", sum); return 0; } int addNumbers (int x, int y) // function definition { int result; result = x + y; return result; // return statement }
Output
Enters two numbers: sum = 40
This program will open the file output.txt
for writing, write the string “Hello, World!” to the file, and then close the file. If the file does not exist, it will be created. If the file already exists, its contents will be overwritten.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment