Pregunta

I am trying to open and then write to a .dat file. The file is just a simple series of numbers, but i would like to add to it. Right now the fputs isn't working for me.

I was wondering if I am using the right function to do the job. Right now it says i can't use the integer enter_this in the function fputs because it is not a constant character.

I want to ask the user to add a integer to the file. My next step after i understand this is to add strings, floats, characters and more. But just getting something that is working is good.

#define _CRT_SECURE_NO_WARNINGS #include #include #include #include #include #include #include #include

//functions called

//why is it void?
int main(void)
{

    FILE *pFile;
    int choice = 0;
    char buf[40];
    int i = 0;
    int num[40];
    int enter_this;

    printf("WELCOME. \n\n");
    pFile = fopen("test.dat", "r");
    if (pFile != NULL)

    for (i = 0; i < 8; i++)
    {
        //get num
        fgets(buf, sizeof(buf), pFile);
        num[i] = atoi(buf);

        printf("#%i = %i\n", i, num[i]);
    }


    printf("Enter number to be added: ");
    gets_s(buf);
    enter_this = atoi(buf);
    fputs(enter_this, pFile);
    fclose(pFile);

    system("pause");

}//end main
¿Fue útil?

Solución

int main(void)

The 'void' in this case implies that the function 'main' accepts no arguments. If you just leave empty parens in C, it implies that the function accepts a variable number of arguments, not 0 as you might expect.

If you want to add a number to the end of the file, you must open it in "append mode":

FILE *pFile = fopen("test.dat", "a");

The second argument "a" is a mode string. It tells fopen to open the file for appending, ie, data will be written at the end of the file. If the file does not exist, it is created. You're currently opening the file in "read only" mode & will not be able to write to it at all. Read about the different mode strings fopen takes here.

Your check to see if the file pointer is NULL is also redundant. You have passed no block to the 'if' to run when the pointer is not NULL. It should be something like:

if (!pFile) {
    puts("Something went wrong");
    exit(1);
}

Finally, fputs takes a STRING value, ie, a character constant. It will refuse to work with enter_this because it is an integer. One way to write the integer to your file is to use fprintf. For example:

/* Write the integer enter_this & a newline to pFile */
fprintf(pFile, "%d\n", enter_this);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top