What is the write() function in C?

Key takeaways:

  • The write() function in C is used to write data to a file and requires three arguments: fileDescriptor, buffer, and bytesToWrite.

  • It returns the number of bytes written, and if an error occurs, it returns -1.

  • The function is used for low-level file manipulation, providing control over file I/O operations, and requires the file to be opened first using open().

  • It's crucial to ensure that bytesToWrite does not exceed the buffer size to avoid overflow issues.

  • The function allows writing partial data from a buffer to a file, useful in scenarios like partial writes or binary data handling.

The write() function

The write() function is a low-level file manipulation function provided by the unistd.h library in C, which performs write operations on a file.

What is the syntax of C write() function?

Below we can see the syntax for the write() function.

int write(int fileDescriptor, void *buffer, size_t bytesToWrite)

We need to provide the function with three arguments which are discussed below:

  1. fileDescriptor: It is an integer file descriptor for the opened file, which the open() function returns when opening a file.

  2. buffer: This pointer points to a buffer containing the data we want to write into the file.

  3. bytesToWrite: Here, we provide an unsigned integer variable that specifies the maximum number of bytes we want to write from the buffer to the file.

When executed, the function returns an integer value of the number of bytes written to the file.

Note: To avoid buffer overflow, the max value of the bytesToWrite variable should not exceed the size of the buffer variable.

C program for write() function

Below, we can see a C program that uses the write() function to write the contents of the buffer to the file sample.txt.

Code for writing the content into a file using write() function

When we run the cat sample.txt command, we see that initially, the sample.txt file is empty.

After running the program via the ./main command, we again print the contents of the sample.txt file. Now we see that it contains the data in the buffer variable.

Code explanation

  • Line 9: We make a character pointer and initialize it with the file name we want to open.

  • Line 11: We open the file via the open() command in read and write mode specified by the second argument O_RDWR.

  • Lines 13–19: Here, we check if the file opened correctly. If it does not, we exit the program with an exit status of 1.

  • Line 21: We make a character pointer named buffer and initialize it with the contents we want to write to the file.

  • Line 23: We call the write() function to write the buffer contents to the file sample.txt. We pass three arguments: the file descriptor fd, the char array buffer, and the maximum number of bytes to write strlen(buffer). The function will return the number of bytes it wrote into the file, which we store in an integer variable bytesWritten.

  • Line 25: Now, we will print the number of bytes that were written to the sample.txt file.

Coding exercise on using the write() function

Now that we understand how to write data to a file using the write() function, let's test ourselves by completing the following code.

In the code file below, we have a buffer object initialized with the string You are stronger than you think and we have an empty text file named file.txt.

Our task is to write 16 characters from the buffer to the file.

Complete the write() function below to write You are stronger into the file, which entails the first 16 bytes of the buffer.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>

int main(){
    
    char* fileName = "file.txt";

    int fd = open(fileName, O_RDWR);
    
    if(fd == -1){
        printf("\nError Opening File!!\n");
        exit(1);
    }
    else{
        printf("\nFile %s opened successfully!\n", fileName);
    }

    char *buffer = "You are stronger than you think\n";

    int bytesWritten = write(/*Write your code here*/);

    printf("%d bytes written successfully!\n", bytesWritten);

    return 0;
}
Challenge for writing a partial text to the file using write() function

Ready to master C programming from the ground up? Our Learn C course covers everything from basic concepts to advanced techniques like dynamic memory allocation, debugging with GDB, and optimizing code with gcc. Gain hands-on experience with C functions, control flow, arrays, strings, pointers, and more to build a strong programming foundation.

Conclusion

The write() function allows developers to write data to files by low-level system calls and ensure that the data is being written to the file due to its return value. It can be used to handle any file writing errors.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to write get function in C

In C, there isn’t a standard function called get(). However, if you’re referring to reading input, commonly used functions are scanf() or getchar(). Here’s an example of how you can write a simple function to get input from the user using getchar():

#include <stdio.h>

char get() {
    char ch;
    ch = getchar();  // Reads a single character from standard input
    return ch;
}

int main() {
    char input = get();  // Calls the get function
    printf("You entered: %c\n", input);
    return 0;
}

What is the use of gets() and puts() functions?

  • The gets() function is used to read a line of text from the standard input. It reads the input until a newline character (\n) is encountered, and stores the string in a buffer. However, gets() is considered risky because it does not check for buffer overflows, which can lead to security vulnerabilities. It is deprecated in modern C standards, and it’s advised to use fgets() instead.
  • The puts() function is used to output a string to the standard output (usually the console), followed by a newline character.

What is the fwrite function in C?

The fwrite() function writes binary and text data from an array to a given data stream.


What is #include stdio.h in C?

#include <stdio.h> is a preprocessor directive in C that includes the Standard Input Output library in your program. This library provides functions for input and output operations, such as printf() for output, scanf() for input, and other file handling functions like fopen(), fclose(), fwrite(), etc.


What is pointer in C?

A pointer in C is a variable that holds the memory address of another variable. Pointers are used to directly access and manipulate memory, allowing for efficient memory management and flexible code (e.g., dynamic memory allocation, passing large data structures to functions, etc.).


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved