Skip to content

Instantly share code, notes, and snippets.

@dlOuOlb
Last active July 23, 2022 11:49
Show Gist options
  • Save dlOuOlb/376668437f369eedc04c16814e4a635e to your computer and use it in GitHub Desktop.
Save dlOuOlb/376668437f369eedc04c16814e4a635e to your computer and use it in GitHub Desktop.
Saving and loading a text file.
#if !__STDC__ || __STDC_VERSION__ < 199901L
# error "This code is written in standard C99."
#else
# include <stdio.h> /* f(close|error|open|read)|size_t */
static signed int xTest_( const size_t Charge, const size_t Budget, char Text[ const restrict static Budget ] ) { return Budget <= Charge || ( Charge[ Text ] = 0 ); }
extern _Bool uLoad_( const size_t Length, char Text[ const restrict static Length ], const char Path[ const restrict static 1U ] )
{
auto const char Mode[ ] = { "r" };
auto FILE *const File = fopen( Path, Mode );
auto signed int Flag = !File;
switch( Flag )
{
case 0:
Flag|= xTest_( fread( Text, sizeof *Text, Length, File ), Length, Text );
Flag|= ferror( File );
Flag|= fclose( File );
default:
return !Flag;
}
}
#endif
#if !__STDC__ || __STDC_VERSION__ < 199901L
# error "This code is written in standard C99."
#else
# include <stdio.h> /* f(close|open|write)|size_t */
# include <string.h> /* size_t|strlen */
extern _Bool uSave_( const char Path[ const restrict static 1U ], const char Text[ const restrict static 1U ] )
{
auto const size_t Length = strlen( Text );
auto const char Mode[ ] = { "w" };
auto FILE *const File = fopen( Path, Mode );
auto signed int Flag = !File;
switch( Flag )
{
case 0:
Flag|= fwrite( Text, sizeof *Text, Length, File ) != Length;
Flag|= fclose( File );
default:
return !Flag;
}
}
#endif
#if !__STDC__ || __STDC_VERSION__ < 199901L
# error "This code is written in standard C99."
#else
# include <stdlib.h> /* EXIT_(FAILURE|SUCCESS) */
# include <string.h> /* strcmp */
extern signed int main( void )
{
extern _Bool
uLoad_( const size_t Length, char Text[ const restrict static Length ], const char Path[ const restrict static 1U ] ),
uSave_( const char Path[ const restrict static 1U ], const char Text[ const restrict static 1U ] );
auto const char
Path[ ] = { "example.txt" },
Source[ ] = { "I am a banana!\n" };
auto char Target[ sizeof Source / sizeof *Source ] = { "" };
return
uSave_( Path, Source ) &&
uLoad_( sizeof Target / sizeof *Target, Target, Path ) &&
!strcmp( Source, Target )?
EXIT_SUCCESS:
EXIT_FAILURE;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment