@bintou
2017-12-06T21:21:10.000000Z
字数 668
阅读 1953
Source
Code
请大家阅读.
/* 本程序展示C语言操作文件的基本方法。
The latest C standard C11 provides a new mode “x” which is exclusive create-and-open mode.
Mode “x” can be used with any “w” specifier, like “wx”, “wbx”.
When x is used with w, fopen() returns NULL if file already exists or could not open.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp = fopen("test.txt", "wx");
if (fp == NULL)
{
puts("Couldn't open file or file already exists");
//exit(0);
}
else
{
fputs("This is a test for FILEs operation.", fp);
puts("Write done.");
fclose(fp);
}
// Open file
fp = fopen("test.txt", "r");
if (fp == NULL)
{
printf("Cannot open file. \n");
exit(0);
}
// Read contents from file
char c = fgetc(fp);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fp);
}
printf("\n");
fclose(fp);
return 0;
}