C Examples Write File
## C Programming: Writing a String to a File
In C programming, file handling is a fundamental concept that allows you to persist data on a storage device. This tutorial demonstrates how to read a string from user input and write it to a text file using standard library functions.
---
### Introduction to File I/O in C
To write data to a file in C, you need to work with a file pointer (`FILE *`) and use standard library functions defined in ``. The general workflow for writing to a file is:
1. **Open the file** using `fopen()` with the appropriate mode (e.g., `"w"` for writing).
2. **Verify** that the file was opened successfully.
3. **Write data** to the file using functions like `fprintf()`, `fputs()`, or `fputc()`.
4. **Close the file** using `fclose()` to free system resources and ensure all buffered data is written to disk.
---
### Code Example: Writing User Input to a File
The following program prompts the user to enter a string, reads the input safely, and writes it to a file named `output.txt`.
```c
#include
#include /* Required for exit() */
int main()
{
char sentence;
FILE *fptr;
// Open the file in write mode ("w")
fptr = fopen("output.txt", "w");
// Check if the file pointer is NULL (indicating an error opening the file)
if (fptr == NULL)
{
printf("Error opening file!\n");
exit(1); // Terminate the program with an error status
}
printf("Enter a string:\n");
// Safely read a line of text from standard input (stdin)
fgets(sentence, sizeof(sentence), stdin);
// Write the string to the file
fprintf(fptr, "%s", sentence);
// Close the file to flush buffers and release the file descriptor
fclose(fptr);
printf("Data successfully written to output.txt\n");
return 0;
}
```
---
### Execution and Output
#### 1. Running the Program
When you compile and run the program, it will prompt you for input:
```bash
Enter a string:
Welcome to YouTip C Programming Tutorials!
Data successfully written to output.txt
```
#### 2. Verifying the File Content
You can verify that the file was created and written to by displaying its contents in your terminal:
```bash
$ cat output.txt
Welcome to YouTip C Programming Tutorials!
```
---
### Key Functions Explained
#### 1. `fopen(const char *filename, const char *mode)`
* **`"w"` (Write Mode):** Opens a file for writing. If the file already exists, its contents are destroyed (truncated to zero length). If the file does not exist, a new file is created.
* **Return Value:** Returns a pointer to a `FILE` object on success, or `NULL` if the file cannot be opened (e.g., due to permission issues or disk space).
#### 2. `fgets(char *str, int n, FILE *stream)`
* Reads a line from the specified stream and stores it into the string pointed to by `str`. It stops when `n-1` characters are read, a newline character is read, or the end-of-file is reached.
* Using `fgets()` is highly recommended over `gets()` because it prevents buffer overflow vulnerabilities by limiting the input size.
#### 3. `fprintf(FILE *stream, const char *format, ...)`
* Works exactly like `printf()`, but instead of printing to the standard output (console), it writes the formatted output to the specified file stream.
#### 4. `fclose(FILE *stream)`
* Closes the stream. Any unwritten buffered data is flushed to the file, and system resources allocated to the stream are released.
---
### Important Considerations
* **Always Check for `NULL`:** Always verify that `fopen()` did not return `NULL` before attempting to write to the file pointer. Accessing a `NULL` pointer will cause a segmentation fault.
* **File Permissions:** Ensure your program has the necessary write permissions in the directory where it is attempting to create or modify the file.
* **Buffer Flushing:** Data written via standard I/O functions is buffered. If your program crashes before `fclose()` is called, some data might not be written to the disk. Calling `fclose()` ensures all buffered data is safely written.
YouTip