[Courses] [C] Beginner's Lesson: How do I...?

KWMelvin kwmelvin at intrex.net
Thu Dec 12 18:10:06 EST 2002


Greetings,

I'm looking for a way to read a text file that was created with the
attached program.  The text file consists of "records" that end with
a newline, and 4 Tab delimited "fields" within each record.  I'd like
to be able to format my output under a "header", something like:

Field1           Field2           Field3           Field4
---------------------------------------------------------------------

I've looked at the functions in strings.h and it looks like strtok()
might be useful?  What else? Can anyone help me with this?  

TIA.
--
K

/* 
create-seq-txt-file.c -- create a sequential text file of records
each "record" ends with a newline
the delimiter between "fields" is a Tab
*/
#include <stdio.h>
#define FILENAME "sample.txt"
int main(void)
{
  char field2[20];
  char field1[20];
  char field3[20];
  char field4[20];
  FILE *fp;

  printf("Enter Ctrl-D to end input.\n");
  if ((fp = fopen(FILENAME, "w")) == NULL)
    printf("File could not be opened\n");
  else
  {
     printf("Enter field1: ");
     fgets(field1, sizeof(field1), stdin);
     if (feof(stdin)) goto end; 
     field1[strlen(field1)-1] ='\t';
        
     printf("Enter field2 : ");
     fgets(field2, sizeof(field2), stdin);
     if (feof(stdin)) goto end;
     field2[strlen(field2)-1] ='\t';
        
     printf("Enter field3  : ");
     fgets(field3, sizeof(field3), stdin);
     if (feof(stdin)) goto end; 
     field3[strlen(field3)-1] ='\t';
        
     printf("Enter field4 : ");
     fgets(field4, sizeof(field4), stdin);
     if (feof(stdin)) goto end;
     field4[strlen(field4)-1] ='\0';
        
     while (!feof(stdin))
     {
       fprintf(fp, "%s%s%s%s\n", field1, field2, field3, field4);

       printf("Enter Ctrl-D to end input.\n");
       printf("Enter field1: ");
       fgets(field1, sizeof(field1), stdin);
       if (feof(stdin)) break;
       field1[strlen(field1)-1] ='\t';
        
       printf("Enter field2 : ");
       fgets(field2, sizeof(field2), stdin);
       if (feof(stdin)) break;
       field2[strlen(field2)-1] ='\t';
        
       printf("Enter field3  : ");
       fgets(field3, sizeof(field3), stdin);
       if (feof(stdin)) break;
       field3[strlen(field3)-1] ='\t';
        
       printf("Enter field4 : ");
       fgets(field4, sizeof(field4), stdin);
       if (feof(stdin)) break;
       field4[strlen(field4)-1] ='\0';
     }
end:
     fclose(fp);
  }
  return 0;
}



More information about the Courses mailing list