File Operations

Libraries Required

1#include <fcntlh>
2#include <unistdh>

Types

1size_t      // is a unsigned integer type used to represent the number of bytes read or written
2ssize_t     // is a signed integer type used to represent the number of bytes read or written
3FILE*       // pointer to struct that represent file stream

open()

Opens a file and returns a file descriptor for it

1int open(const char *pathname, int flags, mode_t mode);

Retrun Value:

  • Success: File descriptor
  • Error: -1

Example:

1int fd = open("exampletxt", O_RDONLY);

read()

Reads data from a file descriptor into a buffer

1ssize_t read(int fd, void *buf, size_t count);

Retrun Value:

  • Success: Number of bytes read
  • Error: -1

Example:

1char buf[128];
2ssize_t nread = read(fd, buf, sizeof buf);

write()

Writes data from a buffer to a file descriptor

1ssize_t write(int fd, const void *buf, size_t count);

Retrun Value:

  • Success: Number of bytes written
  • Error: -1

Example:

1const char *msg = "Hello\n";
2ssize_t nwritten = write(fd, msg, strlen(msg));

close()

Closes an open file descriptor

1int close(int fd);

Retrun Value:

  • Success: 0
  • Error: -1

Example:

1close(fd);

printf()

Writes formatted output to standard output

1int printf(const char *format, );

Return Value:

  • Number of characters printed
  • Negative value if an output error occurs

Examples:

 1// Printing an integer
 2int x = 10;
 3printf("x = %d\n", x);
 4
 5// Printing a float
 6float f = 314;
 7printf("f = %2f\n", f);
 8
 9// Printing a character
10char c = 'A';
11printf("Character: %c\n", c);
12
13// Printing a string
14char str[] = "Hello";
15printf("String: %s\n", str);
16
17// Printing multiple values
18int id = 101;
19char grade = 'A';
20float marks = 895;
21printf("ID: %d, Grade: %c, Marks: %1f\n", id, grade, marks);
22
23// Printing hexadecimal and octal
24int num = 255;
25printf("Hex: %x, Octal: %o\n", num, num);
26
27// Printing a pointer address
28int *ptr = &x;
29printf("Address: %p\n", ptr);

scanf()

Reads formatted input from standard input

1int scanf(const char *format, );

Return Value:

  • Number of items successfully read and assigned
  • EOF if input failure occurs before any conversion

Examples:

 1// Reading an integer
 2int x;
 3scanf("%d", &x);
 4
 5// Reading a float
 6float f;
 7scanf("%f", &f);
 8
 9// Reading a character
10char c;
11scanf(" %c", &c);  // space before %c to skip whitespace
12
13// Reading a string
14char str[100];
15scanf("%s", str);  // stops at first whitespace
16
17// Reading multiple values
18int a, b;
19scanf("%d %d", &a, &b);
20
21// Reading a double
22double d;
23scanf("%lf", &d);
24
25// Reading formatted values into different types
26int id;
27char grade;
28float marks;
29scanf("%d %c %f", &id, &grade, &marks);

dup()

Duplicates an existing file descriptor to the lowest*numbered unused one

1int dup(int oldfd);

Retrun Value:

  • Success: New file descriptor
  • Error: -1

Example:

1int dup_fd = dup(fd);       // dup_fd now refers to the same file

dup2()

Duplicates a file descriptor to a specified descriptor number, closing it first if needed

1int dup2(int oldfd, int newfd);

Retrun Value:

  • Success: New file descriptor
  • Error: -1

Example:

1dup2(fd, STDOUT_FILENO);    // redirect standard output to fd

File Reading Functions

fopen()

Opens a file and returns a file pointer to it

1FILE *fopen(const char *filename, const char *mode);

Return Value:

  • Success: Pointer to FILE
  • Error: NULL

Example:

1FILE *fp = fopen("exampletxt", "r");

fclose()

Closes a previously opened file stream

1int fclose(FILE *stream);
2n

Return Value:

  • Success: 0
  • Error: EOF

Example:

1fclose(fp);

fgets()

Reads a string from a file, stopping at newline or EOF

1char *fgets(char *str, int n, FILE *stream);

Return Value:

  • Success: str
  • Error or EOF: NULL

Example:

1char line[256];
2fgets(line, sizeof line, fp);

fgetc()

Reads a single character from a file

1int fgetc(FILE *stream);

Return Value:

  • Success: Character as an unsigned char cast to int
  • Error or EOF: EOF

Example:

1int ch = fgetc(fp);     // returns int, not char

fread()

Reads binary data from a file stream

1size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

Return Value:

  • Number of full elements successfully read

Example:

1int block[512];
2size_t n = fread(block, 1, sizeof block, fp);

fscanf()

Reads formatted input from a file stream

1int fscanf(FILE *stream, const char *format, );

Return Value:

  • Number of items successfully read and assigned
  • EOF if input failure occurs before any conversion

Example:

1int x, y;
2fscanf(fp, "%d %d", &x, &y);

feof()

Checks whether the end-of-file indicator is set

1int feof(FILE *stream);

Return Value:

  • Non-zero if EOF indicator is set
  • 0 otherwise

Example:

1if (feof(fp)) { /* reached end-of-file */ }

ferror()

Checks whether a file stream has an error

1int ferror(FILE *stream);

Return Value:

  • Non-zero if an error occurred
  • 0 otherwise

Example:

1if (ferror(fp)) { /* handle stream error */ }

fstat()

Gets metadata of a file via file descriptor

1int fstat(int fd, struct stat *statbuf);

Return Value:

  • Success: 0
  • Error: -1

Example:

1int fd = open("example.txt", O_RDONLY);
2fstat(fd, &st);

File Writing Functions

fprintf()

Writes formatted output to a file stream

1int fprintf(FILE *stream, const char *format, );

Return Value:

  • Number of characters printed
  • Negative number on error

Example:

1fprintf(fp, "Value = %d\n", 42);

fputs()

Writes a null-terminated string to a file

1int fputs(const char *str, FILE *stream);

Return Value:

  • Success: Non-negative value
  • Error: EOF

Example:

1fputs("Line of text\n", fp);

fputc()

Writes a single character to a file

1int fputc(int c, FILE *stream);

Return Value:

  • Success: Character written (as unsigned char cast to int)
  • Error: EOF

Example:

1fputc('A', fp);

fwrite()

Writes binary data to a file stream

1size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);

Return Value:

  • Number of full elements successfully written

Example:

1fwrite(block, 1, sizeof block, fp);

fflush()

Flushes a file’s output buffer to disk

1int fflush(FILE *stream);

Return Value:

  • Success: 0
  • Error: EOF

Example:

1fflush(fp);     // force buffered output to disk

Printing Functions

putchar()

Prints a single character to stdout

1int putchar(int char);

Return Value:

  • Success: The character printed
  • Error: EOF

Example:

1putchar('A');    // prints A

puts()

Prints a string followed by a newline to stdout

1int puts(const char *str);

Return Value:

  • Success: Non-negative number
  • Error: EOF

Example:

1puts("Hello");   // prints: Hello\n

printf()

Prints a formatted string to stdout

1int printf(const char *format, );

Return Value:

  • Success: Number of characters printed
  • Error: Negative number

Example:

1printf("Age: %d\n", 25);   // prints: Age: 25

Format Specifiers:

SpecifierMeaning
%dInteger
%fFloating-point
%cCharacter
%sString
%xHexadecimal
%pPointer address
%%Literal %

fprintf()

Prints a formatted string to a file stream

1int fprintf(FILE *stream, const char *format, );

Return Value:

  • Success: Number of characters printed
  • Error: Negative number

Example:

1fprintf(fp, "Score: %d\n", score);   // writes to a file

sprintf()

Prints a formatted string into a buffer (string)

1int sprintf(char *str, const char *format, );

Return Value:

  • Success: Number of characters written
  • Error: Negative number

Example:

1char buffer[100];
2sprintf(buffer, "Name: %s", name);      // buffer gets the formatted string

Unsafe: No bounds checking – risk of buffer overflow

snprintf()

Safer version of sprintf(), limits the output to avoid overflows

1int snprintf(char *str, size_t size, const char *format, );

Return Value:

  • Characters that would have been written (even if truncated)

Example:

1char buf[10];
2snprintf(buf, sizeof(buf), "%d", 1234567890);   // safely formats with limit
Last updated on