-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWritingToAFile.c
More file actions
39 lines (35 loc) · 914 Bytes
/
WritingToAFile.c
File metadata and controls
39 lines (35 loc) · 914 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
int main(void)
{
char buffer[BUFSIZ];
char filename[] = "c:\\temp\\test.txt";
FILE *fp = NULL;
fp = fopen(filename, "w"); /* open file for writing */
if(fp == NULL) /* ALWAYS CHECK RETURN VALUE !!! */
{
printf("Failed to open file for writing\n");
return -1;
}
fputs("Hello world\n", fp); /* write a string to file */
fputc('A', fp); /* write a character to file */
fclose(fp); /* close file */
fp = fopen(filename, "a"); /* open file for appending !!! */
if(fp == NULL)
{
printf("Failed to open file for appending\n");
return -2;
}
fprintf(fp, "\nMy age is %d\n", 99); /* write a formatted string to file */
fclose(fp);
fp = fopen(filename, "r"); /* open file for reading */
if(fp == NULL)
{
printf("Failed to open file for reading\n");
return -3;
}
while(fgets(buffer, BUFSIZ,fp) != NULL)
printf(buffer);
fclose(fp);
printf("%d",BUFSIZ);
return 0;
}