File Handling fprintf error - c

I got an assignment about file handling its all about creating bank accounts then it tells you to input you account number,name,pin,and initial balance. My program does work but it prints wrong on the file. What should I do?
Program:
#include<stdio.h>
#include<conio.h>
#include<windows.h>
#include<ctype.h>
struct accacc
{
char accno[5];
char accna[50];
int accpin[4];
int accba;
};
main()
{
FILE *fp;
struct accacc acc;
char ch;
char t[5];
fp=fopen("Accounts.txt","a");
printf("ENTER ACCOUNT NUMBER:\t");
gets(acc.accno);
printf("ENTER ACCOUNT NAME:\t");
scanf("\n");
gets(acc.accna);
printf("ENTER ACCOUNT PIN:\t");
scanf("%d",&acc.accpin);
printf("ENTER INITIAL BALANCE:\t");
scanf("%d",&acc.accba);
printf("CREATE ANOTHER ONE?:\t");
scanf(" %c",&ch);
fprintf(fp,"%s\t%s\t%d\t%d",acc.accno,acc.accna,acc.accpin,acc.accba);
if(toupper(ch)=='Y')
{
do
{
system("cls");
printf("ENTER ACCOUNT NUMBER:\t");
scanf("\n");
gets(t);
if(strcmp(acc.accno,t)==0)
{
printf("ACCOUNT ALREADY EXISTS!");
}
else
{
printf("ENTER ACCOUNT NAME:\t");
scanf("\n");
gets(acc.accna);
printf("ENTER ACCOUNT PIN:\t");
scanf("%d",&acc.accpin);
printf("ENTER INITIAL BALANCE:\t");
scanf("%d",&acc.accba);
printf("CREATE ANOTHER ONE?:\t");
scanf(" %c",&ch );
fprintf(fp,"%s\t%s\t%d\t\t%d\t\n",t,acc.accna,acc.accpin,acc.accba);
}
}while(toupper(ch)=='Y');
}
else
{
fclose(fp);
}
getch();
}

You passed acc.accpin, which is converted to int* for function parameter to %d in fprintf(), which calls for int, so you invoked undefined behavior.
Fixing other issues, your code may be like this:
#include<stdio.h>
#include<stdlib.h> /* add this to use system() */
#include<string.h> /* add this to use strcmp() */
#include<ctype.h>
struct accacc{
char accno[5];
char accna[50];
int accpin; /* change type from int[4] to int */
int accba;
};
char* safer_gets(char* outbuf, size_t max){
size_t idx = 0;
int input;
if(max == 0) return NULL;
while(idx + 1 < max && (input = getchar()) != EOF && input != '\n'){
outbuf[idx++] = input;
}
if (idx == 0 && input == EOF) return NULL;
outbuf[idx] = '\0';
return outbuf;
}
int main(void){
FILE *fp;
struct accacc acc;
char ch;
char t[5];
fp=fopen("Accounts.txt","a");
if(fp == NULL){ /* add error check */
perror("fopen");
return 1;
}
/* stop using gets() and add error check for input */
printf("ENTER ACCOUNT NUMBER:\t");
if(safer_gets(acc.accno,sizeof(acc.accno)) == NULL){
fputs("input error\n", stderr);
return 1;
}
printf("ENTER ACCOUNT NAME:\t");
scanf("\n");
if(safer_gets(acc.accna,sizeof(acc.accna)) == NULL){
fputs("input error\n", stderr);
return 1;
}
printf("ENTER ACCOUNT PIN:\t");
if(scanf("%d",&acc.accpin) != 1){
fputs("input error\n", stderr);
return 1;
}
printf("ENTER INITIAL BALANCE:\t");
if(scanf("%d",&acc.accba) != 1){
fputs("input error\n", stderr);
return 1;
}
printf("CREATE ANOTHER ONE?:\t");
if(scanf(" %c",&ch) != 1){
fputs("input error\n", stderr);
return 1;
}
fprintf(fp,"%s\t%s\t%d\t%d",acc.accno,acc.accna,acc.accpin,acc.accba);
if(toupper(ch)=='Y'){
do{
system("cls");
printf("ENTER ACCOUNT NUMBER:\t");
scanf("\n");
safer_gets(t,sizeof(t));
if(strcmp(acc.accno,t)==0){
printf("ACCOUNT ALREADY EXISTS!");
}
else {
printf("ENTER ACCOUNT NAME:\t");
scanf("\n");
if(safer_gets(acc.accna,sizeof(acc.accna)) == NULL){
fputs("input error\n", stderr);
return 1;
}
printf("ENTER ACCOUNT PIN:\t");
if(scanf("%d",&acc.accpin) != 1){
fputs("input error\n", stderr);
return 1;
}
printf("ENTER INITIAL BALANCE:\t");
if(scanf("%d",&acc.accba) != 1){
fputs("input error\n", stderr);
return 1;
}
printf("CREATE ANOTHER ONE?:\t");
if(scanf(" %c",&ch ) != 1){
fputs("input error\n", stderr);
return 1;
}
fprintf(fp,"%s\t%s\t%d\t\t%d\t\n",t,acc.accna,acc.accpin,acc.accba);
}
}while(toupper(ch)=='Y');
fclose(fp); /* add fclose() here */
}
else{
fclose(fp);
}
}
Note that the "check for duplicate account number" in this code won't work.

Related

Not able to fetch the data from a temporary file that is from Team_Details.txt, i am not able to fetch the data what ever i had given as input

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
int write()
{
char team_name[50];
int i,n;
printf("------------------------------------------------------");
printf("\n");
printf("Enter number of Teams: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("Team_Detail.txt","a"));
if(fptr==NULL)
{
printf("Error!");
exit(1); // exit(1) (usually) indicates unsucessful termination. However, it's usage is non-portable.
}
for (i=0;i<n;++i)
{
printf("------------------------------------------------------");
printf("\n");
fflush(stdin);
printf("Enter the Team Name:-");
scanf("%[^\n]",team_name);
}
fclose(fptr);
return 0;
}
int display()
{
FILE * fptr;
char buffer[BUFFER_SIZE];
int totalRead = 0 ;
fptr = fopen("Team_Detail.txt","r");
if(fptr == NULL)
{
printf("Unable to open file.\n");
printf("Please check whether file exists or no");
exit(EXIT_FAILURE);
}
printf("------------------------------------------------------");
printf("\n");
while(fgets(buffer, BUFFER_SIZE, fptr ) != NULL)
{
totalRead = strlen(buffer);
buffer[totalRead - 1] = buffer[totalRead - 1] == '\n'
? '\0'
: buffer[totalRead - 1];
printf("%s\n", buffer);
printf("------------------------------------------------------------------------------------------------------------------");
printf("\n");
}
fclose(fptr);
return 0;
}
int main()
{
printf("------------------------------------------------------");
printf("\nFootball League System\n");
printf("------------------------------------------------------");
int choice, num, i;
while(1)
{
printf("\n");
printf(" Press 1 to Enter the Details of the Team \n");
printf(" Press 2 to Display Team Details \n");
printf(" Press 3 to Exit \n");
printf("------------------------------------------------------");
printf("\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
write(); // Here, Calling "team_attributes()" Function
break;
case 2:
display();
break;
case 3:
printf("program finished\n");
exit(0);
break;
default:
printf("Invalid Input entered\n");
}
}
return 0;
}
with the above code I am able give my input and whatever input i give is stored in a temporary text file, but i am unable to display the dat which is present in the temporary text file, Can you guys please help me with this. And also can anyone please suggest me the logic for scheduling matches between the teams by fetching the data of teams temporary text file .
-in your write() you are getting input through scanf(), but not writing them in txt file.
-use functions like fputs() to write the data in txt file.
I'm adding this code to write data in txt file
fputs(team_name,fptr);
Modified version:
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
int write()
{
char team_name[50];
int i,n;
printf("------------------------------------------------------");
printf("\n");
printf("Enter number of Teams: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("Team_Detail.txt","a"));
if(fptr==NULL)
{
printf("Error!");
exit(1); // exit(1) (usually) indicates unsucessful termination. However, it's usage is non-portable.
}
for (i=0;i<n;++i)
{
printf("------------------------------------------------------");
printf("\n");
fflush(stdin);
printf("Enter the Team Name:-");
scanf("%[^\n]",team_name);
fputs(team_name,fptr);
}
fclose(fptr);
return 0;
}
int display()
{
FILE * fptr;
char buffer[BUFFER_SIZE];
int totalRead = 0 ;
fptr = fopen("Team_Detail.txt","r");
if(fptr == NULL)
{
printf("Unable to open file.\n");
printf("Please check whether file exists or no");
exit(EXIT_FAILURE);
}
printf("------------------------------------------------------");
printf("\n");
while(fgets(buffer, BUFFER_SIZE, fptr ) != NULL)
{
totalRead = strlen(buffer);
buffer[totalRead - 1] = buffer[totalRead - 1] == '\n'
? '\0'
: buffer[totalRead - 1];
printf("%s\n", buffer);
printf("------------------------------------------------------------------------------------------------------------------");
printf("\n");
}
fclose(fptr);
return 0;
}
int main()
{
printf("------------------------------------------------------");
printf("\nFootball League System\n");
printf("------------------------------------------------------");
int choice, num, i;
while(1)
{
printf("\n");
printf(" Press 1 to Enter the Details of the Team \n");
printf(" Press 2 to Display Team Details \n");
printf(" Press 3 to Exit \n");
printf("------------------------------------------------------");
printf("\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
write(); // Here, Calling "team_attributes()" Function
break;
case 2:
display();
break;
case 3:
printf("program finished\n");
exit(0);
break;
default:
printf("Invalid Input entered\n");
}
}
return 0;
}

Problems with encrypting a file

I was trying to encrypt a file from a header file and every time I run the program, it deletes the information in the file AccountInformation.txt. Is there any reason why it is deleting the information from AccountInformation.txt and how can I fix my code?
Any help will be great, thank you.
The c code is bellow:
#include <stdio.h>
#include <string.h>
#include "Encryption1.h"
// Variable for signup and login
char fname[120], lname[120], username[120], password[120];
int session;
FILE * accountInfoPointer;
// Main Fucntion for sign up and login
int main (void)
{
// Asking user is they want to sign up or login
printf("What would you like to do?\n");
printf("1. Sign u\n");
printf("2. Login\n");
printf("3. Admin login");
scanf("%d", &session);
// signup
switch(session)
{
case 1:
// Retreiving all of the user's data
printf("What is your FIRST name?\n");
scanf(" %s", fname);
printf("What is your LAST name?\n");
scanf(" %s", lname);
printf("Please enter a username?\n");
scanf(" %s", username);
printf("Create a password\n");
scanf(" %s", password);
accountInfoPointer = fopen("AccountInformation.txt", "a");
fprintf(accountInfoPointer, "Name: %s %s\nUsername: %s\nPassword: %s\n\n", fname, lname, username, password);
fclose(accountInfoPointer);
goto Encrypt; //goes to calender menu
Encrypt:{
//char Title;{
printf("\n\n\t\t\t\t::::::Encrypt::::::\n");
encrypted1(1);
}
break;
}
}
This is the header file code:
#include<stdio.h>
#include<stdlib.h>
int encrypt(void);
int decrypt(void);
int encrypt_view(void);
int decrypt_view(void);
FILE *fp1, *fp2;
char ch;
void encrypted1(int Encrypt)
{
int choice;
while(1)
{
printf("Select One of the Following:\n");
printf("\n1. Encrypt\n");
printf("2. Decrypt\n");
printf("3. View The Encypted File\n");
printf("4. View The Decrypted File\n");
printf("5. Exit\n");
printf("\nEnter Your Choice:\t");
scanf("%d", &choice);
switch(choice)
{
case 1: encrypt();
break;
case 2: decrypt();
break;
case 3: encrypt_view();
break;
case 4: decrypt_view();
break;
case 5: exit(1);
}
}
printf("\n");
// return 0;
}
int encrypt()
{
printf("\n");
fp1 = fopen("AccountInformation.txt","r");
if(fp1 == NULL)
{
printf("Source File Could Not Be Found\n");
}
fp2 = fopen("AccountInformation.txt","w");
if(fp2 == NULL)
{
printf("Target File Could Not Be Found\n");
}
while(1)
{
ch = fgetc(fp1);
if(ch == EOF)
{
printf("\nEnd Of File\n");
break;
}
else
{
ch = ch - (8 * 5 - 3);
fputc(ch, fp2);
}
}
fclose(fp1);
fclose(fp2);
printf("\n");
//return 0;
}
int decrypt()
{
printf("\n");
fp1 = fopen("AccountInformation.txt","r");
if(fp1 == NULL)
{
printf("Source File Could Not Be Found\n");
}
fp2 = fopen("AccountInformation.txt","w");
if(fp2 == NULL)
{
printf("Target File Could Not Be Found\n");
}
while(1)
{
ch = fgetc(fp1);
if(ch == EOF)
{
printf("\nEnd Of File\n");
break;
}
else
{
ch = ch + (8 * 5 - 3);
fputc(ch, fp2);
}
}
fclose(fp1);
fclose(fp2);
printf("\n");
//return 0;
}
int encrypt_view()
{
printf("\n");
fp1 = fopen("AccountInformation.txt","r");
if(fp1 == NULL)
{
printf("No File Found\n");
exit(1);
}
else
{
while(1)
{
ch = fgetc(fp1);
if(ch == EOF)
{
break;
}
else
{
printf("%c", ch);
}
}
printf("\n");
fclose(fp1);
}
printf("\n");
//return 0;
}
int decrypt_view()
{
printf("\n");
fp1 = fopen("AccountInformation.txt","r");
if(fp1 == NULL)
{
printf("No File Found\n");
exit(1);
}
else
{
while(1)
{
ch = fgetc(fp1);
if(ch == EOF)
{
break;
}
else
{
printf("%c", ch);
}
}
printf("\n");
fclose(fp1);
}
// return 0;
printf("\n");
}
fp1 = fopen("AccountInformation.txt","r");
if(fp1 == NULL)
{
printf("Source File Could Not Be Found\n");
}
fp2 = fopen("AccountInformation.txt","w");
if(fp2 == NULL)
{
printf("Target File Could Not Be Found\n");
}
I cringe at this, but the idea should work on unix derivatives. You're clobbering your data because you should have used "r+" but you used "w". The + turns on both read and write, but w+ is going to truncate. You don't want a. Unless you're writing a log file, you don't want a so don't try it here.
At least this problem:
Unable to distinguish all input from fgetc() properly
char, as 8-bit, can encode 256 combinations. int fgetc() returns 257 values: [0-UCHAR_MAX] and EOF.
Code encrypts with ch = ch - (8 * 5 - 3); fputc(ch, fp2); which easily generates a char that collides with EOF on a later read making the file scant.
char ch; // Bad
ch = fgetc(fp1);
if(ch == EOF) // Was ch an EOF or some character?
Use int ch to distinguish the return values from fgetc().
For encryption/decryption, better to open the files in binary mode than text mode. Append a "b".
// fp1 = fopen("AccountInformation.txt","r");
fp1 = fopen("AccountInformation.txt","rb");
Alternative sample code:
int encrypt_view(void) {
printf("\n");
FILE *fp = fopen("AccountInformation.txt", "rb");
if (fp == NULL) {
printf("No File Found\n");
return 1; // Let calling code exit
}
int ch;
while ((ch = fgetc(fp)) != EOF) {
if (ch >= ' ' && ch <= '~') {
printf("%c", ch);
} else {
printf("<%d>", ch);
}
}
printf("\n");
fclose(fp);
return 0;
}

How to give access to text file using if statement?

I am trying to give an if statement to check if a particular name is present in text file, then give access to it otherwise give error message.
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("For person details, please enter the person name: \n");
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
int catch, i=0, index=0;
char ch[100];
printf("Enter your Name: ");
if (scanf("%s", )){ // Don't know what to put here?
perror("Error while reading!");
return 0;
}
catch = fgetc(fr);
while(catch != EOF){
ch[index] = catch;
if (ch[index] == ' '){
ch[index] = '\0';
printf("Here is your result: %s\n",ch);
index = 0;
i++;
}
else
index++;
catch = fgetc(fr);
}
fclose(fr);
return 0;
}
Simply the program firstly opens a file and asks for a user input and verifies if the provided content is case-sensitively matched with the file. If so, then it'll let the program access the entire file and display on the screen, to do that, we must use another FILE b/c the old *fp is already manipulated and in case it's reused, it may display wrong data.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("file.txt", "r"); // for verification
FILE *fp1 = fopen("file.txt", "r"); // for future use
char ch[50], str[50];
short int FLAG = 0;
printf("Enter the string: ");
scanf("%s", &str); // asks for input
while (fscanf(fp, "%s", ch) != EOF) {
if (!strcmp(ch, str)) { // checks if a string matches provided by the user
printf("Found! Here's your details...\n\n");
FLAG = 1;
}
}
if (!FLAG == 1) { // no? exits.
printf("Not found, access denied!\n");
return -1;
}
fclose(fp);
int c = fgetc(fp1); // yes? let's go...
while (c != EOF) {
printf("%c", c); // displays containing data
c = fgetc(fp1);
}
fclose(fp1);
return 0;
}
You'll want to add a variable for your scanf output:
char name[100];
if (scanf("%s", name) != -1)
// ...
Then to compare both you'll use strcmp.
#include <string.h>
//...
if (strcmp(ch, name) == 0)
// both are equal
Note that you can access documentation for scanf and strcmp by typing man scanf or man strcmp in your terminal.
int main()
{
printf("For person details, please enter the person name and id card
number: \n");
printf("Enter your Name: ");
char personName[100];
scanf("%s", personName);
printf("Enter your card number: ");
int cardNumber;
if (scanf("%d", &cardNumber)){
printf("no error detected");
}
else{
printf("error while reading");
}
return 0;
}
The fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
printf("For person details, please enter the person name: \n");
FILE* fr = fopen("/home/bilal/Documents/file.txt", "r");
int catch, i = 0, index = 0;
char ch[100] = { 0 };
if (fr == NULL)
{
perror("Invalid file opening!");
return 1;
}
printf("Enter your Name: ");
fgets(ch, 100, fr);
size_t len = strcspn(ch, "\n");
ch[(len < 100) ? (len) : (99)] = 0; // For file safety checking
if (strlen(ch)) { // Don't know what to put here?
perror("Error while reading!");
return 1;
}
catch = fgetc(fr);
while (catch != EOF) {
ch[index] = catch;
if (ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your result: %s\n", ch);
index = 0;
memset(ch, 0, 100);
i++;
}
else
{
index++;
}
catch = fgetc(fr);
}
fclose(fr);
return 0;
}

The Function Of Displayinfo() does not work it says the file is not created. The Purpose of this Function Is To read a Specific Lines

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Max 500
typedef struct
{
char Matricule[50];
char Model[30];
char Price[30];
int KilometrePerHour;
char Etat[50];
}
Voiture;
Voiture info[Max];
void stockinfo();
void Saveinfo();
void Displayinfo();
void displayAll();
int n;
void stockinfo()
{
int i;
printf("How many Cars You Want To Add ? \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter The Matricule : \n");
scanf("%s", info[i].Matricule);
printf("Enter The Module : \n");
scanf("%s", info[i].Model);
printf("Enter The Price : \n");
scanf("%s", info[i].Price);
printf("Enter The Kilometere Per Hour : \n");
scanf("%d", &info[i].KilometrePerHour);
printf("Enter The Case : \n");
scanf("%s", info[i].Etat);
}
}
void Saveinfo()
{
FILE * save;
save = fopen("CarsParc.doc", "a");
if (save == NULL)
{
printf("The file is Not Created Succefully..\n");
}
else
{
int i;
for (i = 0; i < n; i++)
{
fprintf(save, "\t\tThe Information Of %s Car..\n", info[i].Model);
fprintf(save, "The Matricule :%s\n", info[i].Matricule);
fprintf(save, "The Model :%s\n", info[i].Model);
fprintf(save, "The Price :%s\n", info[i].Price);
fprintf(save, "The Kilometre/h :%d\n", info[i].KilometrePerHour);
fprintf(save, "Tha Case (New/Used) :%s\n", info[i].Etat);
fprintf(save, "\n\n");
}
}
fclose(save);
}
/*i meant this function*/
void Displayinfo()
{
FILE * save;
save = fopen("CarsParc.doc", "r");
if (save == NULL)
{
printf("The file is Not Created Succefully..\n");
}
else
{
char T[100];
char mtrcl[100];
do { fgets(T, 100, save);
printf("Enter The Matricule : \n");
scanf("%s", mtrcl);
int i;
if (strcmp(T, mtrcl) == 0)
{
for (i = 1; i <= 7; i++)
{
fgets(T, 100, save);
printf("%s", T);
}
}
} while (strcmp(T, mtrcl) != 0);
fclose(save);
}
}
void displayAll()
{
FILE * save;
save = fopen("CarsParc.doc", "r");
if (save == NULL)
{
printf("The file is Not Created Succefully..\n");
}
else
{
char copy;
do { copy = fgetc(save);
printf("%c", copy);
} while (copy != EOF);
fclose(save);
}
}
main()
{
/*code */
int choice;
printf("\t\t Welcome To Cars Parc : \n");
printf("1-Add Car : |Click One.. | \n");
printf("2-Search for Specific Car : |Click Two.. |\n");
printf("3-See All The informations : |Click Three..|\n");
scanf("%d", &choice);
system("cls");
do {
if (choice == 1)
{
stockinfo();
Saveinfo();
system("cls");
int back;
printf("The Informations Of This %s Car in Saved Now..\n", info[Max].Model);
printf("To Back To The Menue Click 0 ..\n");
scanf("%d", &back);
if (back == 0)
{
system("cls");
main();
}
else
{
printf("This is The End Of The Programme..");
}
}
if (choice == 2)
{
Displayinfo();
int back;
printf("\n\n\n");
printf("To Back To The Menue Click 0 ..\n");
scanf("%d", &back);
if (back == 0)
{
system("cls");
main();
}
else
{
printf("This is The End Of The Programme..");
}
}
if (choice == 3)
{
displayAll();
int back;
printf("\n\n\n");
printf("To Back To The Menue Click 0 ..\n");
scanf("%d", &back);
if (back == 0)
{
system("cls");
main();
}
else
{
printf("This is The End Of The Programme..");
}
}
} while (choice != 3);
}
You are opening the file for reading ("r"). This will not create it if is does not exist. You need to use the appropriate mode (w or a).
From the man page:
``r'' Open for reading. The stream is positioned at the beginning of
the file. Fail if the file does not exist.
``w'' Open for writing. The stream is positioned at the beginning of
the file. Create the file if it does not exist.
``a'' Open for writing. The stream is positioned at the end of the
file. Subsequent writes to the file will always end up at the
then current end of file, irrespective of any intervening
fseek(3) or similar. Create the file if it does not exist.

(C code) how would I pass my global variables between functions and return them when the main function needs them also?

(C code) how would I pass my global variables between functions and return them when the main function needs them also? I've posted my code below for reference. Of course, I also have a header file with my function prototypes in it as well but they only list variable types inside the closed brackets, not the variable names...
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "myheader.h"
char user_filename[150];
char user_filename2[150];
FILE *fp;
FILE *fp2;
int num_shift;
int main()
{
int choice; // main variables
int option;
char result;
char ch;
int offset;
char character;
int tmp;
option = 0;
num_shift = 0;
strncpy(user_filename, "not set", sizeof("not set"));
strncpy(user_filename2, "not set", sizeof("not set"));
fp = NULL;
fp2 = NULL;
choice = menu(num_shift, user_filename, option); // get user's first selection
while(choice != QUIT) //execute so long as choice is not equal to QUIT
{
switch(choice)
{
case INPUT_FILE:
input(user_filename);
break;
case OUTPUT_FILE:
output();
break;
case NUM_TO_SHIFT:
num_shift = shift(num_shift);
printf ("Shift by %d\n",num_shift);
break;
case ENCODE:
encode(result, ch, num_shift, character);
break;
case QUIT:
quit();
break;
case REVIEW:
review (user_filename);
break;
default:
printf("Oops! An invalid choice slipped through. ");
printf("Please try again.\n");
}
choice = menu(num_shift, user_filename, 0); /* get user's subsequent selections */
}
quit();
}
int menu(int num_shift, char * user_filename, int option)
{
printf("\nText Encoder Service\n\n");
printf("1.\tEnter name of input file (currently '%s')\n", user_filename);
printf("2.\tEnter name of output file (currently '%s')\n", user_filename2);
printf("3.\tEnter number of characters data should be shifted (currently %d)\n", num_shift);
printf("4.\tEncode the text\n");
printf("5.\tReview the text in the input file\n");
printf("\n0.\tQuit\n\n");
printf("Make your selection: \n");
while( (scanf(" %d", &option) != 1) /* non-numeric input */
|| (option < 0) /* number too small */
|| (option > 5)) /* number too large */
{
fflush(stdin); /* clear bad data from buffer */
printf("That selection isn't valid. Please try again.\n\n");
printf("Your choice? ");
}
printf("Selecting %d\n\n", option);
return option;
}
int input(char * user_filename)
{
printf("Enter the filename of the file to encode:\n");
printf("(hit the Enter key when done)\n");
scanf("%s", user_filename);
printf("Getting %s\n\n", user_filename);
fp = fopen (user_filename, "r");
if (fp == NULL)
{
printf("\nSorry, I'm unable to open the file (%s) for reading\n", user_filename);
printf("Please try again.\n");
}
else
{
fclose(fp);
}
return INPUT_FILE;
}
int output()
{
printf("Enter the filename of the output file to store encoded information:\n");
printf("(hit the Enter key when done)\n");
scanf("%s", user_filename2);
printf("Opening File for Writing %s\n\n", user_filename2);
fp2 = fopen (user_filename2, "w");
if (fp2 == NULL)
{
printf("\nSorry, I'm unable to open the file (%s) for writing\n", user_filename2);
printf("Please try again.\n");
} else
{
fclose(fp2);
}
//return user_filename;
return INPUT_FILE;
}
int shift(int num_shift)
{
printf("Enter the number of letters to shift for each character: \n");
printf("(hit the Enter key when done)\n");
scanf("%d", &num_shift);
printf("Setting shift value to: %d\n\n", num_shift);
return num_shift;
}
int encode(char result, char ch, int offset, char character2)
{
int character;
printf("starting encoding with offset of %d\n", offset);
fp = fopen(user_filename, "r");
fp2 = fopen(user_filename2, "w+bc");
if ((fp == NULL) || (fp2 == NULL))
{
printf ("File not found\n");
return (0);
}
fseek(fp, 0, SEEK_SET);
printf("staring Encoding from %s to %s at position %ld\n", user_filename, user_filename2, ftell(fp));
int i = 0;
while(character = fgetc(fp))
{
if ( character == EOF)
{
//printf("%c",character);
//fprintf(fp2,"%c",result);
fclose(fp);
fflush(fp2);
fclose(fp2);
return(0);
}
if (isalpha (character))
{
if (character >= 'a' && character <= 'z')
{
result = character - 'a';
result = (result + offset) % 26; // 26 letters in the alphabet
result += 'a';
if (result < 'a')
{
result = 'z' - ('a' - result)+1;
}
} else if (character >= 'A' && character <= 'Z')
{
result = character - 'A';
result = (result + offset) % 26; // 26 letters in the alphabet
result += 'A';
if (result < 'A')
{
result = 'Z' - ('A' - result)+1;
}
}
//printf("(%c)",result);
} else
{
result = character;
//printf("(%x)", result);
}
printf("%c",result);
fprintf(fp2,"%c",result);
}
return 0;
}
void quit()
{
//fclose(fp);
//fclose(fp2);
printf("Quiting...Bye!");
printf("\n");
exit(0);
}
int review(char * user_filename)
{
char character;
fp = fopen(user_filename, "r");
printf("Showing text from %s file\n", user_filename);
printf("----------BEGIN OF TEXT--------------\n");
while(character = fgetc(fp))
{
if ( character == EOF)
{
printf("%c",character);
printf("\n----------END OF TEXT--------------\n");
fclose(fp);
return(0);
}
printf("%c",character);
}
}
You don't need to pass them around as parameters, you can just access them from anywhere (hence global, well as long as you can see the variable).
Any modifications made to those variables are visible to everyone (aside from multithreading issues) so you have no trouble using them in your functions and in main as well.
You do not need to pass global variables because global variables have global scope, that is they can be accessed anywhere. This is VERY BAD programming practice because it may introduce side-effects later in the program when you decide to use the same name for another purpose for example.
See wikipedia for details.

Resources