From 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 Mon Sep 17 00:00:00 2001 From: Craig Jennings Date: Sun, 7 Apr 2024 13:41:34 -0500 Subject: new repository --- devdocs/c/io%2Ffclose.html | 57 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 devdocs/c/io%2Ffclose.html (limited to 'devdocs/c/io%2Ffclose.html') diff --git a/devdocs/c/io%2Ffclose.html b/devdocs/c/io%2Ffclose.html new file mode 100644 index 00000000..2c80600a --- /dev/null +++ b/devdocs/c/io%2Ffclose.html @@ -0,0 +1,57 @@ +

fclose

Defined in header <stdio.h>
int fclose( FILE *stream );
+

Closes the given file stream. Any unwritten buffered data are flushed to the OS. Any unread buffered data are discarded.

+

Whether or not the operation succeeds, the stream is no longer associated with a file, and the buffer allocated by setbuf or setvbuf, if any, is also disassociated and deallocated if automatic allocation was used.

+

The behavior is undefined if the value of the pointer stream is used after fclose returns.

+

Parameters

+ +
stream - the file stream to close

Return value

​0​ on success, EOF otherwise

+

Example

#include <stdio.h>
+#include <stdlib.h>
+ 
+int main(void)
+{
+    const char* fname = "/tmp/unique_name.txt"; // or tmpnam(NULL);
+    int is_ok = EXIT_FAILURE;
+ 
+    FILE* fp = fopen(fname, "w+");
+    if (!fp) {
+        perror("File opening failed");
+        return is_ok;
+    }
+    fputs("Hello, world!\n", fp);
+    rewind(fp);
+ 
+    int c; // note: int, not char, required to handle EOF
+    while ((c = fgetc(fp)) != EOF) // standard C I/O file reading loop
+        putchar(c);
+ 
+    if (ferror(fp))
+        puts("I/O error when reading");
+    else if (feof(fp)) {
+        puts("End of file is reached successfully");
+        is_ok = EXIT_SUCCESS;
+    }
+ 
+    fclose(fp);
+    remove(fname);
+    return is_ok;
+}

Possible output:

+
Hello, world!
+End of file is reached successfully

References

See also

+ + +
+
(C11)
opens a file
(function)
+
(C11)
open an existing stream with a different name
(function)
C++ documentation for fclose
+

+ © cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
+ https://en.cppreference.com/w/c/io/fclose +

+
-- cgit v1.2.3