C primer plus 文件輸入輸出不完全整理

* exit()函數(shù)關(guān)閉所有打開的文件并終止程序。exit()函數(shù)的參數(shù)會(huì)被傳遞給一些操作系統(tǒng),包括UNIX、Linux和MS DOS,以供其他程序使用。通常的約定是正常終止的程序傳遞值0,非正常終止的程序傳遞非0值。

ANSI C標(biāo)準(zhǔn)規(guī)定使用宏EXIT_SUCCESS來指示程序成功終止,使用宏EXIT_FAILURE來指示程序非成功終止。

return? 和 exit() 的一個(gè)區(qū)別在于,即使在除main()之外的函數(shù)中調(diào)用exit(),它也將終止程序。


* w/w+ 首先將文件長度截為0

rb+ wb ab ab+ a+b wb+ w+b 類似,只是使用二進(jìn)制模式而非文本模式打開文件


* ch=getc(fp);//從指針fp指定的文件中獲取一個(gè)字符

putc(ch,fpout);//將字符寫入fpout指針指定的文件中

* 文件結(jié)尾 getc(fp)==EOF

/* addaword.c -- uses fprintf(), fscanf(), and rewind() */

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAX 41

int main(void)

{

? ? FILE *fp;

? ? char words[MAX];


? ? if ((fp = fopen("wordy", "a+")) == NULL)

? ? {

? ? ? ? fprintf(stdout,"Can't open \"wordy\" file.\n");

? ? ? ? exit(EXIT_FAILURE);

? ? }


? ? puts("Enter words to add to the file; press the #");

? ? puts("key at the beginning of a line to terminate.");

? ? while ((fscanf(stdin,"%40s", words) == 1)? && (words[0] != '#'))

? ? ? ? fprintf(fp, "%s\n", words);


? ? puts("File contents:");

? ? rewind(fp);? ? ? ? ? /* go back to beginning of file */

? ? while (fscanf(fp,"%s",words) == 1)

? ? ? ? puts(words);

? ? puts("Done!");

? ? if (fclose(fp) != 0)

? ? ? ? fprintf(stderr,"Error closing file\n");


? ? return 0;

}


// reducto.c -- reduces your files by two-thirds!

#include <stdio.h>

#include <stdlib.h>? ? // for exit()

#include <string.h>? ? // for strcpy(), strcat()

#define LEN 40

int main(int argc, char *argv[])

{

? ? FILE? *in, *out;? // declare two FILE pointers

? ? int ch;

? ? char name[LEN];? ? // storage for output filename

? ? int count = 0;


? ? // check for command-line arguments

? ? if (argc < 2)

? ? {

? ? ? ? fprintf(stderr, "Usage: %s filename\n", argv[0]);

? ? ? ? exit(EXIT_FAILURE);

? ? }

? ? // set up input

? ? if ((in = fopen(argv[1], "r")) == NULL)

? ? {

? ? ? ? fprintf(stderr, "I couldn't open the file \"%s\"\n",

? ? ? ? ? ? ? ? argv[1]);

? ? ? ? exit(EXIT_FAILURE);

? ? }

? ? // set up output

? ? strncpy(name,argv[1], LEN - 5); // copy filename

? ? name[LEN - 5] = '\0';

? ? strcat(name,".red");? ? ? ? ? ? // append .red

? ? if ((out = fopen(name, "w")) == NULL)

? ? {? ? ? ? ? ? ? ? ? ? ? // open file for writing

? ? ? ? fprintf(stderr,"Can't create output file.\n");

? ? ? ? exit(3);

? ? }

? ? // copy data

? ? while ((ch = getc(in)) != EOF)

? ? ? ? if (count++ % 3 == 0)

? ? ? ? ? ? putc(ch, out);? // print every 3rd char

? ? // clean up

? ? if (fclose(in) != 0 || fclose(out) != 0)

? ? ? ? fprintf(stderr,"Error in closing files\n");


? ? return 0;

}


* fprint()和fscanf()與printf()和scanf()區(qū)別不大,關(guān)鍵在于前兩個(gè)需要第一個(gè)參數(shù)來指定合適的文件

* fgets()和gets()不一樣 他有三個(gè)參數(shù) 第一個(gè)和gets()一樣 都是存儲(chǔ)輸入的地址

fgets(buf, MAX, fp) fgets()函數(shù)讀取到它所遇到的第一個(gè)換行字符的后面,或者讀取比字符串的最大長度MAX少一個(gè)的字符,

或者讀取到文件結(jié)尾,然后fgets()函數(shù)向末尾添加一個(gè)空字符以構(gòu)成一個(gè)字符串。所以,字符串的最大長度代表字符的最大數(shù)目再加上一個(gè)空字符

如果fgets()函數(shù)在達(dá)到字符最大數(shù)目之前讀完了一整行,他將在字符串的空字符之前添加一個(gè)換行符以標(biāo)記一行結(jié)束

而gets()讀取換行符后將其丟棄,fets()函數(shù)可以防止存儲(chǔ)溢出

與gets()類似,fgets()遇到EOF會(huì)返回NULL

fputs()兩個(gè)參數(shù),依次是一個(gè)字符串的地址和和一個(gè)文件指針 與puts()不同,fputs()函數(shù)打印時(shí)不添加換行符


/* reverse.c -- displays a file in reverse order */

#include <stdio.h>

#include <stdlib.h>

#define CNTL_Z '\032'? /* eof marker in DOS text files */

#define SLEN 81

int main(void)

{

? ? char file[SLEN];

? ? char ch;

? ? FILE *fp;

? ? long count, last;


? ? puts("Enter the name of the file to be processed:");

? ? scanf("%80s", file);

? ? if ((fp = fopen(file,"rb")) == NULL)

? ? {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? /* read-only mode? */

? ? ? ? printf("reverse can't open %s\n", file);

? ? ? ? exit(EXIT_FAILURE);

? ? }


? ? fseek(fp, 0L, SEEK_END);? ? ? ? /* go to end of file */

? ? last = ftell(fp);

? ? for (count = 1L; count <= last; count++)

? ? {

? ? ? ? fseek(fp, -count, SEEK_END); /* go backward? ? ? */

? ? ? ? ch = getc(fp);

if (ch != CNTL_Z && ch != '\r')? /* MS-DOS files */

? ? ? ? ? ? putchar(ch);

? ? }

? ? putchar('\n');

? ? fclose(fp);


? ? return 0;

}


* fseek()第一個(gè)參數(shù)為FILE指針,第二個(gè)為偏移量,第三個(gè)為模式(SEEK_SET 文件開始處;SEEK_CUR 文件當(dāng)前處;SEEK_END 文件結(jié)尾處)

偏移量 0L 10L 2L -10L

ftell為long類型 返回文件的當(dāng)前位置 ftell(fp)


* size_t fwrite(const void * restrict ptr, size_t size, size_t nmemb, FILE * restrict fp) 將二進(jìn)制數(shù)據(jù)寫入文件

ptr--數(shù)據(jù)塊地址 size--數(shù)據(jù)塊大小(以字節(jié)為單位) nmemb--數(shù)據(jù)塊的數(shù)目 fp--要寫入的文件

size_t fread(const void * restrict ptr, size_t size, size_t nmemb, FILE * restrict fp) 讀取通過fwrite()寫入的文件數(shù)據(jù)

ptr--讀入文件數(shù)據(jù)的內(nèi)存存儲(chǔ)地址 fp--要寫入的文件

double earnings[10];

fread(earnings, sizeof(double), 10, fp);//該調(diào)用將10個(gè)double值復(fù)制到earnings數(shù)組中


* 把多個(gè)文件的內(nèi)容追加到一個(gè)文件中

/* append.c -- appends files to a file */

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define BUFSIZE 4096

#define SLEN 81

void append(FILE *source, FILE *dest);

char * s_gets(char * st, int n);

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

? ? int ch;


? ? puts("Enter name of destination file:");

? ? s_gets(file_app, SLEN);

? ? if ((fa = fopen(file_app, "a+")) == NULL)

? ? {

? ? ? ? fprintf(stderr, "Can't open %s\n", file_app);

? ? ? ? exit(EXIT_FAILURE);

? ? }

? ? if (setvbuf(fa, NULL, _IOFBF, BUFSIZE) != 0)

? ? {

? ? ? ? fputs("Can't create output buffer\n", stderr);

? ? ? ? exit(EXIT_FAILURE);

? ? }

? ? puts("Enter name of first source file (empty line to quit):");

? ? while (s_gets(file_src, SLEN) && 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 appending. %d files appended.\n", files);

? ? rewind(fa);

? ? printf("%s contents:\n", file_app);

? ? while ((ch = getc(fa)) != EOF)

? ? ? ? putchar(ch);

? ? puts("Done displaying.");

? ? 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);

}

char * s_gets(char * st, int n)

{

? ? char * ret_val;

? ? char * find;


? ? ret_val = fgets(st, n, stdin);

? ? if (ret_val)

? ? {

? ? ? ? find = strchr(st, '\n');? // look for newline

? ? ? ? if (find)? ? ? ? ? ? ? ? ? // if the address is not NULL,

? ? ? ? ? ? *find = '\0';? ? ? ? ? // place a null character there

? ? ? ? else

? ? ? ? ? ? while (getchar() != '\n')

? ? ? ? ? ? ? ? continue;

? ? }

? ? return ret_val;

}


* 使用二進(jìn)制I/O進(jìn)行隨機(jī)存取

/* randbin.c -- random access, binary i/o */

#include <stdio.h>

#include <stdlib.h>

#define ARSIZE 1000

int main()

{

? ? double numbers[ARSIZE];

? ? double value;

? ? const char * file = "numbers.dat";

? ? int i;

? ? long pos;

? ? FILE *iofile;


? ? // create a set of double values

? ? for(i = 0; i < ARSIZE; i++)

? ? ? ? numbers[i] = 100.0 * i + 1.0 / (i + 1);

? ? // attempt to open file

? ? if ((iofile = fopen(file, "wb")) == NULL)

? ? {

? ? ? ? fprintf(stderr, "Could not open %s for output.\n", file);

? ? ? ? exit(EXIT_FAILURE);

? ? }

? ? // write array in binary format to file

? ? fwrite(numbers, sizeof (double), ARSIZE, iofile);

? ? fclose(iofile);

? ? if ((iofile = fopen(file, "rb")) == NULL)

? ? {

? ? ? ? fprintf(stderr,

? ? ? ? ? ? ? ? "Could not open %s for random access.\n", file);

? ? ? ? exit(EXIT_FAILURE);

? ? }

? ? // read selected items from file

? ? printf("Enter an index in the range 0-%d.\n", ARSIZE - 1);

? ? while (scanf("%d", &i) == 1 && i >= 0 && i < ARSIZE)

? ? {

? ? ? ? pos = (long) i * sizeof(double); // calculate offset

? ? ? ? fseek(iofile, pos, SEEK_SET);? ? // go there

? ? ? ? fread(&value, sizeof (double), 1, iofile);

? ? ? ? printf("The value there is %f.\n", value);

? ? ? ? printf("Next index (out of range to quit):\n");

? ? }

? ? // finish up

? ? fclose(iofile);

? ? puts("Bye!");


? ? return 0;

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容