user1593866
user1593866

Reputation: 17

(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);
    }

}

Upvotes: 1

Views: 3749

Answers (2)

user126992
user126992

Reputation: 39

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.

Upvotes: 1

Jesus Ramos
Jesus Ramos

Reputation: 23266

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.

Upvotes: 2

Related Questions