Question

I am trying to learn the syntax for writing data(chars, integers and strings). I have studied the contents of the following link http://web.cs.swarthmore.edu/~newhall/unixhelp/C_files.html and written the following code. The aim of the code is to store the data in the text file in the following manner:

33
Hello

15
Ok

if I make the following inputs 33, Hello, 15, Ok and 0. But the text file is completely blank when I open it after running the program. Is there anyone here that is skilled in storing data in a text document that can give me some hints in what I am doing wrong? Or if there is any other good tutorials that you know?

My test code is attached below[I can compile and run it without any problem except that it doesn't do the things that I expect:( ]

char stdin_buff[20];
int stdin_int;
FILE *fp;
char *filename = "data.txt"; //name of the textfile where the data should be stored 

void handle_String_input(char msg[]){
    fp = fopen(filename, "w"); //opens the text file in write mode
    if(fp==NULL){
        printf("Unable to open the file! \n");
    }
    fseek(fp, 1, SEEK_END); //seek the end of the text file
    fputs(msg,fp); //writes the message to the text file
    putc('\n',fp); //new line in the text document
    putc('\n',fp); //new line in the text document 
    fclose(fp); //closes the text file
}

void handle_Integer_input(int nbr){
    fp = fopen(filename, "w"); //opens the text file in write mode
    if(fp==NULL){
        printf("Unable to open the file! \n");
    }
    fseek(fp, 1, SEEK_END); //seek the end of the text file
    fputc(nbr,fp); //writes the nbr into the text file 
    putc('\n',fp); //new line in the text document 
    fclose(fp); //closes the text file
}

void main(){
    while(1){
        memset(stdin_buff,'\0',10); //clears the content of stdin_buff 
        printf("Enter an integer(enter 0 to exit): ");
        fgets(stdin_buff,9,stdin); //retrieves an input from keyboard(the user is expected to only use the numbers 0-9)
        stdin_int=atoi(stdin_buff);
        handle_Integer_input(stdin_int);
        if(stdin_int==0){
            break;
        }
        memset(stdin_buff,'\0',10); //clears the content of stdin_buff 
        printf("Enter a string(enter 0 to exit): ");
        fgets(stdin_buff,9,stdin); //retrieves input from keyboard
        handle_String_input(stdin_buff);
        if(stdin_buff[0]=='0'){
            break;
        }
    }
}

What have I missed/ not understood? Any suggestions on improvements are appreciated!

Was it helpful?

Solution

In the fopen statement, use "a" (for append) instead of "w". "w" clears the file.

Currently, if you end your interactive session by entering an integer '0', then the file will appear empty. If you end with a string '0' you should see just the character 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top