Skip to content

Instantly share code, notes, and snippets.

@Adobe-Android
Last active February 26, 2019 00:33
Show Gist options
  • Save Adobe-Android/7a9aebbdad69efad8f69325f491d1c54 to your computer and use it in GitHub Desktop.
Save Adobe-Android/7a9aebbdad69efad8f69325f491d1c54 to your computer and use it in GitHub Desktop.
Read in a file and handle errors and write to a file and handle errors
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define bufSize 1024
int main(int argc, char const *argv[])
{
FILE *in;
char buf[bufSize];
if (!(in = fopen("test.txt", "r"))) {
fprintf(stderr, "Can't open the file.\n");
return 1;
}
while (fgets(buf, sizeof(buf), in) != NULL)
{
buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
printf("%s\n", buf);
}
fclose(in);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
const char* text = "Write this to the file";
FILE *out;
if (!(out = fopen("output.txt", "w"))) {
fprintf(stderr, "Can't write to the file.\n");
return 1;
}
fprintf(out, text);
fclose(out);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment