Search code examples
cstackpostfix-mta

File Handling and export into text file


I need your help please. I want to export the output of my code into a text file. and i really don't know how to deal with it. Could someone please help me figuring this out. Thank you so much

So here's my code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct node {
int data;
struct node *next;
};
struct node *top = NULL;

struct node* createNode(int data){
struct node *p = (struct node *) malloc(sizeof (struct node));
p->data = data;
p->next = NULL;
}

void push (int data){
    struct node *ptr = createNode(data);
    if (top == NULL){
        top = ptr;
    return;
    }
    ptr->next = top;
    top = ptr;
}

int pop(){
    int data;
    struct node *temp;
    if (top == NULL)
        return -1;
    data = top->data;
    temp = top;
    top =top->next;
    free(temp);
return (data);
}

int main(){
        char str[100];
        int i = 0, data = -1, operand1, operand2, result;
        printf("Expression in postfix format: ");
        fgets(str, 99, stdin);
            for (; i < strlen(str); i++){
                if (isdigit(str[i])){
                data = (data == -1) ? 0 : data;
                data = (data * 10) + (str[i] - 48);
                continue;
            }
            if (data != -1){
            push(data);
            }
            if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/'){
            operand2 = pop();
            operand1 = pop();
                if (operand1 == -1 || operand2 == -1)
                    break;

        switch (str[i]){
            case '+':
                    result = operand1 + operand2;
                    push(result);
                    break;
            case '-':
                    result = operand1 - operand2;
                    push(result);
                    break;
            case '*':
                    result = operand1 * operand2;
                    push(result);
                    break;
            case '/':
                    result = operand1 / operand2;
                    push(result);
                    break;
                }
            }
                    data = -1;
        }
                    if (top != NULL && top->next == NULL)
                        printf("Postfix Evaluation: %d\n", top->data);
                    else
                        printf("Invalid Expression!\n");
        return 0;

}


Solution

  • In main you must open the file:

    FILE *fp;
    fp = fopen ("whatever.txt", "w+"); // w+ mean that you open the file 
                                       // write and read, but if it
                                       // not exist, will be made.
    

    and change the printf with fprintf :

    fprintf(fp, "%d\n", i); // you must add the name of the file where to
                            // print your stuff (fp)
    

    At the end of main, remember to close the file connection:

    fclose (fp);