QUESTION 03
Name character and line-based file I/O functions.
2 marksAnswer
fgetc and fputc read or write characters; fgets and fputs handle bounded input lines or output strings. Check each operation’s documented result.
QUESTION 03
fgetc and fputc read or write characters; fgets and fputs handle bounded input lines or output strings. Check each operation’s documented result.
QUESTION 04
Text streams can be processed a character, formatted field or line at a time.
Store fgetc’s result in int so it can distinguish EOF from character values. fputc writes one character and reports failure with EOF. The loop while ((ch = fgetc(fp)) != EOF) processes successfully read characters; after it ends, inspect ferror if the difference between an error and normal end matters.
fprintf writes values using a format string. fscanf interprets input fields and returns the number of assignments completed, or its specified failure indication. Match each conversion to the actual destination type. Bound string conversions and do not assume a failed conversion leaves a usable new value.
fgets reads at most capacity - 1 characters and terminates successfully read text. A newline is retained if read. fputs writes the string without adding its own newline. puts, in contrast, writes to stdout and adds a newline.
Use characters for byte-oriented text transformations, formats for a controlled field layout, and bounded lines when spaces matter. A long input line can span more than one fgets call; decide whether to process chunks or reject an overlong record.
Scanning n characters is O(n) character work. A fixed-size line buffer adds O(1) space with respect to the whole file length. The total file need not be loaded into memory. The sample writes two lines and prints them using a checked read loop.
This demonstration creates or replaces its codebhavya_* sample file in the working directory. Run it in a separate test directory. Native binary examples use one compatible implementation.
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
int main(void)
{
const char *path = "codebhavya_text_demo.txt";
FILE *fp = fopen(path, "w");
if (fp == NULL) { puts("Open failed"); return 1; }
if (fputs("First line\nSecond line\n", fp) == EOF) { fclose(fp); puts("Write failed"); return 1; }
if (fclose(fp) != 0) { puts("Close failed"); return 1; }
fp = fopen(path, "r");
if (fp == NULL) { puts("Open failed"); return 1; }
char line[80];
while (fgets(line, sizeof line, fp) != NULL) { fputs(line, stdout); }
int failed = ferror(fp);
if (fclose(fp) != 0 || failed) { puts("Read/close failed"); return 1; }
return 0;
}The example uses values in the code.
First line
Second line