File Handling Functions in C
1. fopen()
Definition: Opens a file and returns a file pointer (FILE *). If the file doesn't exist, it can create it
(depending on mode).
Syntax: FILE *fopen(const char *filename, const char *mode);
Example: FILE *fp = fopen("data.txt", "r");
Output: Opens the file 'data.txt' in read mode.
2. fclose()
Definition: Closes an open file.
Syntax: int fclose(FILE *stream);
Example: fclose(fp);
Output: Closes the file pointed by 'fp'.
3. fgetc()
Definition: Reads a single character from the file.
Syntax: int fgetc(FILE *stream);
Example: char ch = fgetc(fp);
Output: Reads one character from the file pointed by 'fp'.
4. fgets()
Definition: Reads a string (line) from the file until a newline or EOF is reached.
Syntax: char *fgets(char *str, int n, FILE *stream);
Example: fgets(buffer, 100, fp);
Output: Reads up to 100 characters or until a newline from the file.
5. fputc()
Definition: Writes a single character to the file.
Syntax: int fputc(int ch, FILE *stream);
Example: fputc('A', fp);
Output: Writes the character 'A' to the file.
6. fputs()
Definition: Writes a string to the file.
Syntax: int fputs(const char *str, FILE *stream);
Example: fputs("Hello", fp);
Output: Writes the string 'Hello' to the file.
7. fscanf()
Definition: Reads formatted input from the file (similar to scanf but from a file).
Syntax: int fscanf(FILE *stream, const char *format, ...);
Example: fscanf(fp, "%d %s", &num, str);
Output: Reads an integer and a string from the file.
8. fprintf()
Definition: Writes formatted output to a file (similar to printf but to a file).
Syntax: int fprintf(FILE *stream, const char *format, ...);
Example: fprintf(fp, "%d %s", num, str);
Output: Writes an integer and a string to the file.
9. feof()
Definition: Returns true (non-zero) if the end of the file has been reached.
Syntax: int feof(FILE *stream);
Example: while (!feof(fp)) { ... }
Output: Returns non-zero when the end of the file is reached.
10. ferror()
Definition: Checks for any error in the file operations.
Syntax: int ferror(FILE *stream);
Example: if (ferror(fp)) { ... }
Output: Returns non-zero if an error occurred while reading/writing the file.
11. rewind()
Definition: Resets the file pointer to the beginning of the file.
Syntax: void rewind(FILE *stream);
Example: rewind(fp);
Output: Moves the file pointer back to the start of the file.
12. ftell()
Definition: Returns the current position of the file pointer.
Syntax: long ftell(FILE *stream);
Example: long pos = ftell(fp);
Output: Returns the current file pointer position in bytes.
13. fseek()
Definition: Moves the file pointer to a specific position.
Syntax: int fseek(FILE *stream, long offset, int origin);
Example: fseek(fp, 0, SEEK_END);
Output: Moves the file pointer to the end of the file.