文件的读取

(1)文件的操作,文件的打开:打开一个文件,FILE *fopen(char *filename,char * mode)

若想打开file文件进行写操作,可以试用一下的方式:

FILE *fp;
if (fp = fopen("file", "w") == NULL){
    printf("file cannot be opened\n");
    exit(1);
}
else{
    printf("file opened for writing\n");
}

(2)文件的关闭:程序对文件的读写操作完成后,必须关闭文件,这是因为对打开的磁盘文件进行写入时,若文件的缓冲区没有被文件写满,这些内容将不会自动写入文件中,从而导致内容的丢失,只有对打开的文件进行关闭操作时,停留在文件缓冲区中的内容才能写入文件的磁盘上,保证文件的完整性。

int fclose(FILE *stream);

若成功地关闭文件,则返回一个0值,不成功关闭则返回一个非0值。

文件读取的例子:


//
文件的打开FILE * fp=fopen("filename","mode"); //将文件指针关闭,将文件缓冲区的数据写入磁盘文件中,同步数据。 //将文件进行顺序读取,按字符读取,ch=fgetc(fp),将文件顺序写出 #include<iostream> using namespace std; int main(){ FILE * fp;//获取文件结构指针 char ch; if ((fp = fopen("E:\\360MoveData\\Users\\Administrator\\Desktop\\practice\\dict.txt", "r")) == NULL){ printf("file cannot be opened\n"); exit(1); } while ((ch = fgetc(fp)) != EOF){ fputc(ch, stdout); } fclose(fp); return 0; }
#include<iostream>
using namespace std;
int main(){
    FILE *fp;
    char str;
    if ((fp = fopen("E:\\360MoveData\\Users\\Administrator\\Desktop\\practice\\goldstine.txt", "w")) == NULL){
        printf("file cannot be opened\n");
        exit(1);
    }
    while ((str = fgetc(stdin)) != '\n'){
        fputc(str, fp);
    }
    fclose(fp);
    return 0;
}

(3)文件的字符串读取

char *fgets(char *str,int n,FILE *stream)

表示充缓冲区stream中读取n-1个字符到str所指的字符数组中。如果遇到\n或者文件的结尾EOF,则停止读取,在读取完成后会在字符数组的结尾添加一个'\0',所以总共还是读取了n个字符。

//一行一行读取文件中的数据
#include<iostream>
using namespace std;
int main(){
    FILE * fp;
    char buff[64];
    if ((fp = fopen("E:\\360MoveData\\Users\\Administrator\\Desktop\\practice\\dict.txt", "r"))==NULL){
        printf("file cannot be opened\n");
        exit(1);
    }
    while (!feof(fp)){
        if (fgets(buff, 64, fp) != NULL){
            printf("%s", buff);
        }
    }
    fclose(fp);
    return 0;
}

(4)文件的字符串写

int fputs(char *str,FILE * stream)

函数fputs将str指针指明的字符数组写入到stream指定的文件中去,该字符以'\0'结束,但这个字符并不写入文件中去,str指向的字符串也可以用数组代替,或用字符常量代替;

c = fputs("computer\0",fp)
将字符常量写入fp中,函数正确执行后返回0,否则返回-1

#include<iostream>
using namespace std;
int main(){
    FILE *fp;
    char buff[64];
    if ((fp = fopen("E:\\360MoveData\\Users\\Administrator\\Desktop\\practice\\goldstine.txt", "a")) == NULL){
        printf("file cannot be opened\n");
        exit(1);
    }
    while (strlen(fgets(buff, 64, stdin)) > 1){
        fputs(buff, fp);
        fputs("\n", fp);
    }

    fclose(fp);
    return 0;
}

文件的格式化读写

文件的随机读写

 

posted @ 2020-09-18 22:55  goldstine  阅读(242)  评论(0)    收藏  举报