demotext.c

Index vorige Seite nächste Seite
/*
+-------------------------------+
| Demo program for textfile ops |
| (c) 2001 Ulrich Kritzner      |
+-------------------------------+
| important functions:          |
|            fopen              |
|            fclose             |
|            fscanf             |
|            fprintf            |
+-------------------------------+
| see also manpage for:         |
|            fgets              |
|            fputs              |
+-------------------------------+
*/

#include <stdio.h>

#define TEXT_FILE_NAME "./demotext.file"

void read_from_console(int *i,float *f,char *s);
void write_to_console(int i,float f,char *s);

void write_to_file(void)
{
  FILE *file;
  int i;
  float f;
  char s[100];
  read_from_console(&i,&f,&s[0]);
  printf("\n\nput values into file...\n");
  file=fopen(TEXT_FILE_NAME,"wt");         /* <---------------------- */
  fprintf(file,"%i  %f  %s\n",i,f,&s[0]);  /* <---------------------- */
  fclose(file);                            /* <---------------------- */
  write_to_console(i,f,&s[0]);
}

void read_from_file(void)
{
  FILE *file;
  int i;
  float f;
  char s[100];
  printf("\n\nget values from file...\n");
  file=fopen(TEXT_FILE_NAME,"rt");      /* <---------------------- */
  fscanf(file,"%i%f%99s",&i,&f,&s[0]);  /* <---------------------- */
  fclose(file);                         /* <---------------------- */
  write_to_console(i,f,&s[0]);
}

int main(int _argc,char *_argv[],char *_envp[])
{
  printf("demo prog for text file operations\n");
  write_to_file();
  read_from_file();
}

void read_from_console(int *i,float *f,char *s)
{
  int retvalue;
  printf("\nenter any integer value: ");
  retvalue=scanf("%i",i);
  if (retvalue<1) {
    printf("error: input was no integer value. exit.\n");
    exit(0);
  }
  printf("\nenter any floating point value: ");
  retvalue=scanf("%f",f);
  if (retvalue<1) {
    printf("error: input was no floating point value. exit.\n");
    exit(0);
  }
  printf("\nenter any character string: ");
  retvalue=scanf("%99s",s);
  if (retvalue<1) {
    printf("error: not able to read character string. exit.\n");
    exit(0);
  }
}

void write_to_console(int i,float f,char *s)
{
  int retvalue;
  printf("i= %i       f= %0.3f       s= %s\n",i,f,s);
}

Index vorige Seite nächste Seite

Autor: Ulrich Kritzner