C/File/File Write — различия между версиями

Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
(нет различий)

Текущая версия на 10:22, 25 мая 2010

Read and write array into file

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  FILE *fp;
  float floatValue[5] = { 1.1F, 2.2F, 3.3F, 4.4F, 5.5F };
  int i;
  if((fp=fopen("test", "wb"))==NULL) {
    printf("Cannot open file.\n");
  }
  if(fwrite(floatValue, sizeof(float), 5, fp) != 5)
    printf("File read error.");
  fclose(fp);
  /* read the values */
  if((fp=fopen("test", "rb"))==NULL) {
    printf("Cannot open file.\n");
  }
  if(fread(floatValue, sizeof(float), 5, fp) != 5) {
    if(feof(fp))
       printf("Premature end of file.");
    else
       printf("File read error.");
  }
  fclose(fp);
  for(i=0; i<5; i++)
    printf("%f ", floatValue[i]);
  return 0;
}


Redirect the printf to file

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  FILE *fp;
  printf("This will display on the screen.\n");
  if((fp=freopen("OUT", "w" ,stdout))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  printf("This will be written to the file OUT.");
  fclose(fp);
  return 0;
}


Save and read string into a file

#include <stdio.h>
#include <stdlib.h>
double d[10] = {
  1.2, 1.7, 1.3, 1.9, 0.7,
  1.4, 7.4, 0.0, 1.1, 5.5
};
int main(void)
{
  int i;
  FILE *fp;
  if((fp = fopen("my.txt", "wb"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  for( i = 0; i < 10; i++)
    if(fwrite(&d[i], sizeof( double ), 1, fp) != 1) {
      printf("Write error.\n");
      exit(1);
    }
  fclose(fp);
  if((fp = fopen("my.txt", "rb"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  /* clear the array */
  for(i = 0; i < 10; i++) 
      d[i] = -1.0;
  for(i = 0; i < 10; i++)
    if(fread(&d[i], sizeof(double), 1, fp) != 1) {
      printf("Read error.\n");
      exit(1);
    }
  fclose(fp);
  /* display the array */
  for(i = 0; i < 10; i++) 
      printf("%f ", d[i]);
  return 0;
}


Save and write different type of value into file

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  FILE *fp;
  int i;
  /* open file for output */
  if((fp = fopen("my.txt", "wb"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  i = 10;
  if(fwrite(&i, sizeof(int), 1, fp) != 1) {
    printf("Write error occurred.\n");
    exit(1);
  }
  fclose(fp);
  /* open file for input */
  if((fp = fopen("my.txt", "rb"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  if(fread(&i, sizeof i, 1, fp) != 1) {
    printf("Read error occurred.\n");
    exit(1);
  }
  printf("i is %d",i);
  fclose(fp);
  return 0;
}


Save string into file: fputs

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
  char str[80];
  FILE *fp;
  if((fp = fopen("TEST", "w"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  do {
    printf("Enter a string (CR to quit):\n");
    gets(str);
    strcat(str, "\n");  /* add a newline */
    fputs(str, fp);
  } while(*str!="\n");
  return 0;
}


Save text content into a file

#include <stdio.h>
int main(){
   char *proverbs[] ={"AAA\n","BBB\n","CCC\n"};
   char more[60] = "DDD\n";
   FILE *pfile = NULL;
   int i = 0;
   char *filename = "C:\\myfile.txt";
   pfile = fopen(filename, "w");
   if(pfile == NULL)
   {
     printf("Error opening %s for writing. Program terminated.", filename);
   }
   for(i = 0 ; i < sizeof proverbs/sizeof proverbs[0] ; i++)
     fputs(proverbs[i], pfile);
   fclose(pfile);
   pfile = fopen(filename, "a");          /* Open it again to append data */
   if(pfile == NULL)
   {
     printf("Error opening %s for writing. Program terminated.", filename);
   }
   fputs(more, pfile);
   fclose(pfile);
   pfile = fopen(filename, "r");           /* Open the file to read it */
   if(pfile == NULL)
   {
     printf("Error opening %s for writing. Program terminated.", filename);
   }
   while(fgets(more, 60, pfile) != NULL)
    printf("\n%s", more);
  fclose(pfile);
  remove(filename);
}


Use fprintf to save

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  FILE *fp;
  if((fp=fopen("test", "wb"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  fprintf(fp, "this is a test %d %f", 10, 20.01);
  fclose(fp);
  return 0;
}


Write a block of data to a stream: how to use fwrite

#include <stdio.h>
int main ()
{
  FILE *file;
  char str[] = "This buffer contains 34 characters";
  file = fopen ("my.txt" , "w");
  fwrite (str , 1 , 34 , file);
  fclose (file);
  return 0;
}


Write and read the entire array in one step

#include <stdio.h>
#include <stdlib.h>
double d[10] = {
  1.3, 1.7, 1.23, 1.9, 0.97,
  1.5, 7.4, 0.0, 1.01, 8.75
};
int main(void)
{
  int i;
  FILE *fp;
  if((fp = fopen("my.txt", "wb")) == NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  /* write the entire array in one step */
  if( fwrite(d, sizeof d, 1, fp) != 1) {
    printf("Write error.\n");
    exit(1);
  }
  fclose(fp);
  if((fp = fopen("my.txt", "rb"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  /* clear the array */
  for(i = 0; i < 10; i++) 
      d[i] = 0.0;
  /* read the entire array in one step */
  if(fread(d, sizeof d, 1, fp) != 1) {
    printf("Read error.\n");
    exit(1);
  }
  fclose(fp);
  /* display the array */
  for(i = 0; i < 10; i++) 
      printf("%f ", d[i]);
  return 0;
}


Write character to stdout: how to use fputchar

/* fputchar example: alphabet writer */
#include <stdio.h>
int main ()
{
   char c;
   for (c = "A" ; c <= "Z" ; c++)
     fputchar (c);
   return 0;
}


Write character to stdout: how to use putchar

#include <stdio.h>
int main ()
{
  char c;
  
  for (c = "A" ; c <= "Z" ; c++) {
        putchar (c);
  }
  
  return 0;
}


Write character to stream: how to use fputc

#include <stdio.h>
int main ()
{
  FILE *file;
  char c;
  file = fopen ("my.txt","w");
  
  if (file!=NULL)
  {
    for (c = "a" ; c <= "z" ; c++)
    {
      fputc (c , file);
    }
    fclose (file);
  }
  return 0;
}


Write character to stream: how to use putc

#include <stdio.h>
int main ()
{
  FILE *file;
  char c;
  file=fopen("my.txt", "wt");
  
  for (c = "a" ; c <= "z" ; c++) {
        putc (c , file);
  }
  fclose (file);
  return 0;
}


write non string content

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  FILE *fp;
  float f=12.23;
  if((fp=fopen("test", "wb"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  fwrite(&f, sizeof(float), 1, fp);
  fclose(fp);
  return 0;
}


Write out file

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int cur_char;
    FILE *out_file;
    out_file = fopen("test.out", "w");
    if (out_file == NULL) {
        fprintf(stderr,"Can not open output file\n");
        exit (8);
    }
    for (cur_char = 0; cur_char < 128; ++cur_char) {
        fputc(cur_char, out_file);
    }
    fclose(out_file);
    return (0);
}


Write some non-character data to a disk file and read it back

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  FILE *fp;
  double d = 1.23;
  int i = 10;
  long l = 13333023L;
  if(( fp = fopen("my.txt", "wb+")) == NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  fwrite(&d, sizeof(double), 1, fp);
  fwrite(&i, sizeof(int), 1, fp);
  fwrite(&l, sizeof(long), 1, fp);
  rewind(fp);
  fread(&d, sizeof(double), 1, fp);
  fread(&i, sizeof(int), 1, fp);
  fread(&l, sizeof(long), 1, fp);
  printf("%f %d %ld", d, i, l);
  fclose(fp);
  return 0;
}


Write string to a stream: how to use fputs

#include <stdio.h>
int main ()
{
   FILE *file;
   char str[256];
   printf ("Enter string to append: ");
   fgets (str, 255, stdin);
   
   file = fopen ("my.txt","at");
   fputs (str,file);
   fclose (file);
   return 0;
}


Writing a file a character at a time

#include <stdio.h>
#include <string.h>
int main()
{
   char mystr[80]="asdfasdf";
   int i = 0;
   int lstr = 0;
   int mychar = 0;
   FILE *pfile = NULL;
   char *filename = "C:\\myfile.txt";
   pfile = fopen(filename, "w");
   if(pfile == NULL)
   {
     printf("Error opening %s for writing. Program terminated.", filename);
   }
   lstr = strlen( mystr );
   for(i = lstr-1 ; i >= 0 ; i--)
     fputc(mystr[i], pfile);  /* Write string to file backwards */
   fclose(pfile);
   /* Open the file for reading */
   pfile = fopen(filename, "r");
   if(pfile == NULL)
   {
     printf("Error opening %s for reading. Program terminated.", filename);
   }
   /* Read a character from the file and display it */
   while((mychar = fgetc(pfile)) != EOF)
     putchar(mychar);
   putchar("\n");
   fclose(pfile);
   remove(filename);
}


Writing names and phone numbers to a file

/*
Beginning C, Third Edition
 By Ivor Horton
 ISBN: 1-59059-253-0
 Published: Apr 2004
 Publisher: apress
*/
/*
  This solution uses a PhoneRecord structure with the name and number stored in
  arrays with a fixed size. This allows the file operations to be very simple.
  You can just read or write a PhoneRecord structure since its size is fixed.
  If you wanted to allocate space for the name and number dynamically, then
  you would have to explicitly write the name and number strings as well as the
  PhoneRecord structure to the file. You would also need to include the length of each
  data item in the file so you knew how much to read back.
*/
#include <stdio.h>
#define FIRST_NAME_LENGTH  31
#define SECOND_NAME_LENGTH 51
#define NUMBER_LENGTH      21
#define TRUE                1
#define FALSE               0
/* Structure defining a name */
struct Name
{
  char firstname[FIRST_NAME_LENGTH];
  char secondname[SECOND_NAME_LENGTH];
};
/* Structure defining a phone record */
struct PhoneRecord
{
  struct Name name;
  char number[NUMBER_LENGTH];
};
/* Function prototypes */
struct PhoneRecord read_phonerecord();              /* Read a name and number from the keyboard     */
struct Name read_name();                            /* Read a name from the keyboard                */
void show_record(struct PhoneRecord record);        /* Output name and number from a phone record   */
struct PhoneRecord find_numbers(struct Name name);  /* Find numbers corresponding to a given name   */
void add_record();                                  /* Add a new name and number                    */
void delete_records(struct Name name);              /* Delete records for a given name              */
void list_records();                                /* List all the records in the file             */
void show_operations();                             /* Displays operations supported by the program */
int equals(struct Name name1, struct Name name2);   /* Compare two names for equality               */
/* Global variables */
FILE *pFile = NULL;                                 /* File pointer                           */
char *filename = "C:\\records.bin";                 /* Name of the file holding the records   */
char answer = "n";                                  /* Stores input responses                 */

void main()
{
  show_operations();                                /* Display the available operations */     
  for(;;)
  {
    printf("\nEnter a letter to select an operation: ");
    scanf(" %c", &answer);
    switch(toupper(answer))
    {
      case "A":                                     /* Add a new name and number record  */
        add_record();
        break;
      case "D":                                     /* Delete records for a given name   */
        delete_records(read_name());
        break;
      case "F":                                     /* Find the numbers for a given name */
        find_numbers(read_name());
        break;
      case "L":                                     /* List all the name/number records  */
        list_records();
        break;
      case "Q":                                     /* Quit the program                 */
        return;
      default:
        printf("\nInvalid selection try again.");
        show_operations();
        break;
    }
  }
 }
/* Reads a name and number from the keyboard and creates a PhoneRecord structure */
struct PhoneRecord read_phonerecord()
{
  struct PhoneRecord record;    
  record.name = read_name();
  printf("Enter the number: ");
  scanf(" %[ 0123456789]",record.number);  /* Read the number - including spaces */
  return record;
}
/* Outputs the name and number from a phone record */
void show_record(struct PhoneRecord record)
{
  printf("\n%s %s   %s", record.name.firstname,record.name.secondname, record.number);
}
/* Add a new name and number */
void add_record()
{
  struct PhoneRecord record;
  if((pFile = fopen(filename, "a+")) == NULL)  /* Open/create file to be written in append mode */
  {
    printf("Error opening %s for writing. Program terminated.", filename);
    abort();
  }
  record = read_phonerecord();                 /* Read the name and number */  
  fwrite(&record, sizeof record, 1, pFile);
  fclose(pFile);                               /* Close file               */ 
  printf("\nNew record added.");
}
/* Read a name from the keyboard and create a Name structure for it */
struct Name read_name()
{
  struct Name name;
    printf("Enter a first name: ");
    scanf(" %s", &name.firstname);
    printf("Enter a second name: ");
    scanf(" %s", &name.secondname);
  return name;
}
/* Delete records for a given name */
/* To delete one or more records we can copy 
   the contents of the existing file to a new 
   file, omitting the records that are to be
   deleted. We can then delete the old file and
   rename the new file to have the old file
   name.
*/
void delete_records(struct Name name)
{
  FILE *pNewFile = NULL;
  char *pnewfilename = NULL;
  struct PhoneRecord record;
  if((pFile = fopen(filename, "r")) == NULL)         /* Open current file to read it */
  {
    printf("Error opening %s for reading. Program terminated.", filename);
    abort();
  }
  pnewfilename = tmpnam(NULL);                       /* Create temporary file name      */
  if((pNewFile = fopen(pnewfilename, "w")) == NULL)  /* Open temporary file to write it */
  {
    printf("Error opening %s for writing. Program terminated.", pnewfilename);
    fclose(pFile);
    abort();
  }
  /* Copy existing file contents to temporary file, omitting deleted records */
  for(;;)
  {
    fread(&record, sizeof record, 1, pFile);      /* Read a record      */
    if(feof(pFile))                               /* End of file read ? */
      break;                                      /* Yes-quit copy loop */
    if(equals(name, record.name))                 /* Is the record this name ?      */
    {
      printf("\nFound a record:");                /* Ys, so it"s a delete candidate */
      show_record(record);
      printf("\nDo you really want to delete it(y or n)? ");
      scanf(" %c", &answer);
      if(tolower(answer) == "y")                  /* If it"s to be deleted */
        continue;                                 /* Skip the copying      */
    }
    fwrite(&record, sizeof record, 1, pNewFile);  /* copy current record   */
  }
  fclose(pFile);
  fclose(pNewFile);
  if((pNewFile = fopen(pnewfilename, "r")) == NULL)   /* Open temporary file to read it */
  {
    printf("Error opening %s for reading. Program terminated.", pnewfilename);
    abort();
  }
  if((pFile = fopen(filename, "w"))==NULL)            /* Open original file to write it */
  {
    printf("Error opening %s for writing. Program terminated.", filename);
    abort();
  }
  /* Copy contents of new temporary file back to old file          */
  /* This overwrites the original contents because the mode is "w" */
  for(;;)
  {
    fread(&record, sizeof record, 1, pNewFile);   /* Read temporary file */
    if(feof(pNewFile))                            /* If we read EOF */
      break;                                      /* We are done    */
    fwrite(&record, sizeof record, 1, pFile);     /* Write record to original file */
  }
  fclose(pFile);                       /* Close the original file   */
  fclose(pNewFile);                    /* Close the temporary file  */
  remove(pnewfilename);                /* Delete the temporary file */
  printf("Delete complete.");
}
/* List all the records in the file */
void list_records()
{
  struct PhoneRecord record;
  int file_empty = TRUE;    /* File empty flag */
  if((pFile = fopen(filename, "r")) == NULL)   /* Open the file to read it */      
  {
    printf("Error opening %s for reading. Program terminated.", filename);
    abort();
  }
  /* List the file contents */
  for(;;)
  {
    fread(&record, sizeof record, 1, pFile);
    if(feof(pFile))
      break;
    file_empty = FALSE;          /* We got a record so set empty flag false */
    show_record(record);         /* output the record                       */
  }
  fclose(pFile);                 /* Close the file */
  /* Check whether there were any records */
  if(file_empty)
    printf("The file contains no records.\n");
  else
    printf("\n");
}
/* Displays the operations that are supported by the program */
void show_operations()
{
  printf("The operations available are:"
    "\nA: Add a new name and number entry."
    "\nD: Delete all existing entries for a name."
    "\nF: Find the number(s) for a given name."
    "\nL: List all the entries in the file."
    "\nQ: Quit the program.");
}
/* Find numbers corresponding to a given name */
struct PhoneRecord find_numbers(struct Name name) 
{
  struct PhoneRecord record;
  int name_found = FALSE;                    /* Name found flag */
  if((pFile = fopen(filename, "r")) == NULL) /* Open the file to read it */      
  {
    printf("Error opening %s for reading. Program terminated.", filename);
    abort();
  }
  /* Search the records read from the file */
  for(;;)
  {
    fread(&record, sizeof record, 1, pFile);  /* Read a record */
    if(feof(pFile))
      break;
   if(equals(name,record.name))               /* Is it the name requested? */
   {
     if(!name_found)                          /* Is this the first time we found it? */
     {
       name_found = TRUE;                        /* Yes so set flag to true */
       printf("The numbers for this name are:"); /* Output initial message  */
     }
     printf("\n%s",record.number);               /* Output the number       */
   }
  }
  fclose(pFile);                                 /* Close the file */
  /* Check for name not found */
  if(!name_found)
    printf("The name was not found.\n");
  else
    printf("\n");
}
/* Compare two names for equality */
int equals(struct Name name1, struct Name name2)
{
  return (strcmp(name1.firstname, name2.firstname)==0) && (strcmp(name1.secondname, name2.secondname)==0);
}


Writing strings to a file

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 50
int main()
{
  FILE *pFile = NULL;
  char *filename = "C:\\myfile.txt";
  char buffer[80] = "asdf";
  int buffer_size = BUFFER_SIZE;
  size_t str_length = 0;
  pFile = fopen(filename, "w");
  if(pFile == NULL)
  {
    printf("Error opening %s for writing. Program terminated.", filename);
    abort();
  }
  str_length = strlen(buffer);
  fwrite(&str_length, sizeof(size_t), 1, pFile);
  fwrite(buffer, str_length, 1, pFile);
  fclose(pFile);
  printf("\nFile write complete\n");
  if(buffer != NULL)
    free(buffer);
 }