欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言File文件操作函数学习

程序员文章站 2024-03-17 18:41:16
...

C语言File文件操作函数学习

(禁止转载)

(content from 《C Primer Plus, Fifth Edition》 By Stephen Prata)


· Functions:
fopen(), getc(), putc(), exit(), fclose()
fprintf(), fscanf(), fgets(), fputs()
fread(), fwrite()


fopen()

该函数可以用来打开一个文件,同时可以根据第二参数决定对该文件的操作类型。

具体格式例如:

FILE *fp;

fp=fopen(“test.txt”,”w+x”);  //加x后,若文件存在,则打开失败,防止改写原文件

"r"

read: Open file for input operations. The file must exist.

"w"

write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.

"a"

append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseekfsetposrewind) are ignored. The file is created if it does not exist.

"r+"

read/update: Open a file for update (both for input and output). The file must exist.

"w+"

write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.

"a+"

append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseekfsetposrewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.

"rb", "wb", "ab",
"ab+", "a+b", "wb+",
"w+b", "ab+", "a+b"

Like the preceding modes, except it uses binary mode instead of
text mode
(二进制形式操作)

Read(读操作) write(写操作) append(添加操作)

#include <stdio.h>
#include <stdlib.h> // ANSI C exit() prototype
int main(int argc, char *argv[])
{
    int ch; // place to store each character as read
    FILE *fp; // "file pointer"
    long count = 0;
    if (argc != 2)
    {
        printf("Usage: %s filename\n", argv[0]);
        exit(1);
    }
    if ((fp = fopen(argv[1], "r")) == NULL)
    {
        printf("Can't open %s\n", argv[1]);
        exit(1);
    }
    while ((ch = getc(fp)) != EOF)
    {
        putc(ch,stdout); // same as putchar(ch);
        count++;
    }
    fclose(fp);
    printf("File %s has %ld characters\n", argv[1], count);
    return 0;
}

getc() and putc() 

该函数用来读取文件中的内容。

具体格式例如:

ch = getc(fpin);//read from file

putc(ch,fpout);//write to file

 

int ch; // int to hold EOF
FILE * fp;
fp = fopen("wacky.txt", "r");
ch = getc(fp); // get initial input
while (ch != EOF)
{
    putchar(ch); // process input
    ch = getc(fp); // get next input
}

 

exit() and fclose()

fclose()函数的作用是关闭文件。

具体格式例如:

fclose(fp)

exit()函数的作用为退出程序,它即使不在main函数内,也可以退出整个程序。

 

if (fclose(fp) != 0)
    printf("Error in closing file %s\n", argv[1]);

 

fprintf(), fscanf(), fgets(), and fputs()

fprintf(), fscanf()这两个函数的操作类似于printf()函数,只是这两个函数是写入文件。

具体使用格式例如:

fscanf(fp,"%s",words);

fprintf(fp, "%s ", words);

fgets(buf, MAX, fp);//buf是一个数组,fp是文件指针,MAX为字符串的最大长度

fputs(buf, fp);

#include <stdio.h>
#include <stdlib.h>
#define MAX 40
int main(void)
{
    FILE *fp;
    char words[MAX];
    if ((fp = fopen("wordy", "a+")) == NULL)
    {
        fprintf(stdout,"Can't open \"words\" file.\n");
        exit(1);
    }
    puts("Enter words to add to the file; press the Enter");
    puts("key at the beginning of a line to terminate.");
    while (gets(words) != NULL && words[0] != '\0')
        fprintf(fp, "%s ", words);
    puts("File contents:");
    rewind(fp); /* go back to beginning of file */
    while (fscanf(fp,"%s",words) == 1)
        puts(words);
    if (fclose(fp) != 0)
        fprintf(stderr,"Error closing file\n");
    return 0;
}

 

#include <stdio.h>
#define MAXLINE 20
int main(void)
{
    char line[MAXLINE];
    while (fgets(line, MAXLINE, stdin) != NULL && line[0] != '\n')
        fputs(line, stdout);
    return 0;
}


fread() and fwrite()

这两个函数提供二进制操作。

具体使用格式例如:

double earnings[10];
fread(earnings, sizeof (double), 10, fp);

char buffer[256];
fwrite(buffer, 256, 1, fp);

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 1024
#define SLEN 81
void append(FILE *source, FILE *dest);
int main(void)
{
    FILE *fa, *fs;// fa for append file, fs for source file
    int files = 0; // number of files appended
    char file_app[SLEN]; // name of append file
    char file_src[SLEN]; // name of source file
    puts("Enter name of destination file:");
    gets(file_app);
    if ((fa = fopen(file_app, "a")) == NULL)
    {
        fprintf(stderr, "Can't open %s\n", file_app);
        exit(2);
    }
    if (setvbuf(fa, NULL, _IOFBF, BUFSIZE) != 0)
    {
        fputs("Can't create output buffer\n", stderr);
        exit(3);
    }
    puts("Enter name of first source file (empty line to quit):");
    while (gets(file_src) && file_src[0] != '\0')
    {
        if (strcmp(file_src, file_app) == 0)
        fputs("Can't append file to itself\n",stderr);
        else if ((fs = fopen(file_src, "r")) == NULL)
        fprintf(stderr, "Can't open %s\n", file_src);
        else
        {
            if (setvbuf(fs, NULL, _IOFBF, BUFSIZE) != 0)
                {
                    fputs("Can't create input buffer\n",stderr);
                    continue;
                }
            append(fs, fa);
            if (ferror(fs) != 0)
                fprintf(stderr,"Error in reading file %s.\n",file_src);
            if (ferror(fa) != 0)
                fprintf(stderr,"Error in writing file %s.\n",file_app);
            fclose(fs);
            files++;
            printf("File %s appended.\n", file_src);
            puts("Next file (empty line to quit):");
        }
    }
    printf("Done. %d files appended.\n", files);
    fclose(fa);
    return 0;
}
void append(FILE *source, FILE *dest)
{
    size_t bytes;
    static char temp[BUFSIZE]; // allocate once
    while ((bytes = fread(temp,sizeof(char),BUFSIZE,source)) > 0)
        fwrite(temp, sizeof (char), bytes, dest);
}