/***********************************************************
File I/O: Simple
2/1/00
Katie Rivard
gets the user's username, adds .txt to it, creates a file,
writes standard "hello world" string, reads it back.
***********************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getusername();
char username[30]; /*global variables username and filename*/
char filename[30];
main()
{
int let=getusername(), i=1, b=1;
char dotend[]=".txt";
/**/int n1=2;
char c, n2[10], n3[10];
FILE *iofp;
strcpy(filename, username);
strcat(filename, dotend); /*creates valid, appended filename*/
printf("Your filename is: %s\n", filename);
if((iofp=fopen(filename, "w+"))==NULL) /*opens and checks file*/
{
fprintf(stderr, "Can't open file %s!\n", filename);
return 0;
}
else
{
printf("File opened smoothly.\n");
printf("File contains:\t"); /*prints current contents of file*/
do
{
c=fscanf(iofp, "%s", &n2);
if(c!=EOF)
printf(" %s",n2);
}while (c!=EOF);
printf("\n");
}
printf("Printing \"Hello, world!\" to file...\n");
fprintf(iofp, "Hello, World!\n"); /*prints "hello world"*/
fseek(iofp, 0, SEEK_SET); /*file pointer moved to beg of file*/
printf("File now contains:\t");
do
{
c=fscanf(iofp, "%s", &n3);
if(c!=EOF)
printf(" %s",n3);
}while (c!=EOF);
printf("\n");
return 0;
}
int getusername() /*getusername(): recieves username from the keyboard, returns the last char/array cell used #*/
{
int i, endchar;
scanf("%s", &username);
for(i=0; i<30; i++)
{
if (username[i]=='\0')
{
endchar=i;
break;
}
}
return endchar;
}