Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

fopen — C23 stream function

`fopen(filename, mode)` from `<stdio.h>` opens the named file, associates it with a new `FILE` stream, and returns its pointer or null on failure. Modes `r`, `w`, and `a`, optional `+` and `b`, and `x` only in the enumerated `w`-based modes select access, creation, truncation, append, and exclusive creation.

Version: C23

Syntax

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

fopen(filename, mode) from <stdio.h> opens the named file, associates it with a new FILE stream, and returns its pointer or null on failure. Modes r, w, and a, optional + and b, and x only in the enumerated w-based modes select access, creation, truncation, append, and exclusive creation.

The example opens its own file with fopen(name, "w+"), writes 42, rewinds, reads the value, closes, and removes the file. Output 1 42 demonstrates a successful update-mode open and a valid write-to-read transition after positioning.

w can truncate an existing file, a directs every write to the current end, and x in an allowed w mode requires creation without replacement; x is not a flag for r or a. Always test null and check fclose. On an update stream, output→input requires fflush or a positioning function, whereas input→output requires positioning unless the input operation encountered EOF.

Examples

#include <stdio.h>
int main(void){const char *name="c_ref_20_demo.tmp";FILE *s=fopen(name,"w+");if(!s)return 1;int opened=1;if(fputs("42",s)==EOF){fclose(s);remove(name);return 1;}rewind(s);int value=0;if(fscanf(s,"%d",&value)!=1){fclose(s);remove(name);return 1;}int closed=fclose(s);int removed=remove(name);printf("%d %d\n",opened,value);return closed==0&&removed==0?0:1;}

Result

1 42

The example opens its own file with `fopen(name, "w+")`, writes `42`, rewinds, reads the value, closes, and removes the file. Output `1 42` demonstrates a successful update-mode open and a valid write-to-read transition after positioning.

Sources