Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #define SIZE 100
- int main() {
- // Pointer to the memory where the FILE structure is stored
- FILE *fp;
- // Opening a file for writing
- fp = fopen("example.txt", "w");
- if (fp == NULL) {
- printf("Error while opening the file");
- return 0;
- }
- // Writing to a file with appropriate format
- fprintf(fp, "%s\n", "Example:");
- // Writing to a file character by character
- char text[80] = "Structured Programming Exam Exercises";
- char *p = text;
- while (*p) {
- int result = fputc((int) *p, fp);
- if (result == EOF) {
- printf("Error while writing to file\n");
- }
- p++;
- }
- // Closing a file
- fclose(fp);
- // Opening a file for reading
- fp = fopen("example.txt", "r");
- if (fp == NULL) {
- printf("Error while opening the file");
- return 0;
- }
- // Reading a file character by character
- int ch;
- while (1) {
- ch = fgetc(fp);
- if (ch == EOF) {
- break;
- }
- printf("%c", (char) ch);
- }
- // Reading a file word by word
- char word[SIZE];
- while (fscanf(fp, "%s", word) != NULL) {
- // Do something with the word
- }
- // Reading a file row by row
- char row[SIZE;
- while (fgets(row, SIZE, fp)) {
- // Do something with the row
- }
- // Closing a file
- fclose(fp);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement