YouTip LogoYouTip

C Function Fwrite

# C Library Function - `fwrite()` The `fwrite()` function is a standard C library function defined in the `` header. It is used to write block data (binary or text) from a memory buffer to a specified output stream. It is particularly useful for writing arrays, structures, and other complex data types directly to files. --- ## Description The `fwrite()` function writes up to `nmemb` elements, each of size `size` bytes, from the memory block pointed to by `ptr` to the given output `stream`. The file position indicator for the stream is advanced by the total number of bytes successfully written. --- ## Syntax The function prototype for `fwrite()` is as follows: ```c size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); ``` ### Parameters * **`ptr`**: A pointer to the array of elements or memory block to be written. * **`size`**: The size of each element to be written, in bytes (typically specified using the `sizeof` operator). * **`nmemb`**: The number of elements to write, where each element has a size of `size` bytes. * **`stream`**: A pointer to a `FILE` object that specifies the destination output stream. ### Return Value * **On Success**: The function returns the total number of elements successfully written, represented as a `size_t` integer. * **On Error or EOF**: If the returned value is less than `nmemb`, an error has occurred or the end of the file was reached. You can use `ferror()` or `feof()` to determine the exact cause. --- ## Code Examples ### Example 1: Writing a String to a File The following example demonstrates how to write a character array (string) to a text file using `fwrite()`. ```c #include int main() { FILE *fp; char str[] = "This is youtip.com"; // Open file for writing fp = fopen("file.txt", "w"); if (fp == NULL) { perror("Error opening file"); return -1; } // Write the string (including the null terminator) to the file fwrite(str, sizeof(str), 1, fp); // Close the file stream fclose(fp); return 0; } ``` **Output:** This program creates a file named `file.txt` containing the following text: ```text This is youtip.com ``` --- ### Example 2: Reading and Displaying the File Content To verify the contents of the file created in the previous example, you can use the following program to read and print its characters: ```c #include int main() { FILE *fp; int c; // Open the file in read-only mode fp = fopen("file.txt", "r"); if (fp == NULL) { perror("Error opening file"); return -1; } // Read character by character until the end of the file while (1) { c = fgetc(fp); if (feof(fp)) { break; } printf("%c", c); } fclose(fp); return 0; } ``` --- ### Example 3: Writing and Reading Structures (Binary Mode) `fwrite()` is highly efficient for writing binary structures directly to disk. Here is an example of writing a struct to a binary file and reading it back. ```c #include struct Student { int id; char name; float gpa; }; int main() { FILE *fp; struct Student s1 = {101, "Alice Smith", 3.9}; struct Student s2; // 1. Write struct to binary file fp = fopen("student.bin", "wb"); if (fp != NULL) { fwrite(&s1, sizeof(struct Student), 1, fp); fclose(fp); } // 2. Read struct back from binary file fp = fopen("student.bin", "rb"); if (fp != NULL) { fread(&s2, sizeof(struct Student), 1, fp); printf("Student ID: %d\n", s2.id); printf("Student Name: %s\n", s2.name); printf("Student GPA: %.2f\n", s2.gpa); fclose(fp); } return 0; } ``` --- ## Important Considerations 1. **Binary vs. Text Mode**: When writing non-text data (like structs, integers, or raw bytes), always open the file in binary mode (`"wb"` or `"ab"`). On some operating systems (like Windows), text mode (`"w"`) translates newline characters (`\n` to `\r\n`), which can corrupt binary data. 2. **Return Value Validation**: Always check if the return value of `fwrite()` matches the `nmemb` parameter. If the returned value is smaller than expected, it indicates a write error (e.g., disk full, permission denied, or invalid file descriptor). 3. **Buffer Flushing**: `fwrite()` is a buffered I/O function. Data may not be written to the physical disk immediately. Use `fflush()` or close the file with `fclose()` to ensure all buffered data is written.
← C Function SetbufC Function Ftell β†’