Reading and writing strings in C.


Source listing
//----------------------------------------------------------
// File: Code601_FileIO.cpp
// Purpose: Demonstration of string I/O in ANSI Standard C
// Programming Language: C
// Author: Dr. Rick Coleman
//-----------------------------------------------------------
#include <stdio.h>
#include <string.h>

int main(void)
{
    FILE *fptr;        // pointer to FILE

    char string[81];     // Use 80 char lines
    fptr = fopen("textfile.txt","w");
    //-----------------------------------------------
    //  Writing strings to a file
    //  I/O function:  int fputs(char *string, File *fptr)
    //-----------------------------------------------
    while (strlen(gets(string)) > 0)
        {
            fputs(string, fptr); // write string
            fputs("\n", fptr);   // write newline 
        }
    fclose(fptr);

    //-------------------------------------------------------------
    //  Reading strings from a file
    //  I/O function:  char *fgets(char *string, int n, File *fptr)
    //--------------------------------------------------------------
    if((fptr = fopen("textfile.txt","r"))==NULL)
    {
        printf("Can't open textfile.txt.\n");
        return 0;
    }
    while (fgets(string,80,fptr) != NULL)
    {
        string[strlen(string)-1] = '\0';
        printf("%s\n", string);
    }
    fclose(fptr);
    return 0;
}