一个C语言程序输出序号和单词,#include #include #define MAX 40int main(void

1个回答

  • #include

    #include

    #define MAX 40

    int main(void)

    {

    FILE *fp;

    char words[MAX];

    int wordct = 0;

    if ((fp = fopen("wordy","a+")) == NULL) //打开文件,是指针fp指向文件wordy

    {

    fprintf(stderr,"Can't open "words" file.n");

    exit(1);

    }

    /* determine current number of entries */

    rewind(fp); //rewind()是一个反绕函数,作用是使指针回到文件的开头,在对文件读写的过程中,指针是一直变化的,但是这个函数会把指针重新置在文件的开头

    while (fgets(words,MAX - 1,fp) != NULL) // 统计文件中单词个数

    wordct++;

    rewind(fp);

    puts("Enter words to add to the file.Enter one word per line,and ");

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

    while (gets(words) != NULL && words[0] != ' ')

    fprintf(fp,"%d:%sn",++wordct,words); //追加新单词到文件中,并标注序号wordct

    puts("File contents:");

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

    while (fgets(words,MAX - 1,fp) != NULL)

    fputs(words,stdout);

    if (fclose(fp) != 0)

    fprintf(stderr,"Error closing filen");

    return 0;}