Search code examples
ceclipse-luna

How to write in txt file using C by Eclipse (typing by console)


I was trying to find an answer for this in some internet pages, at the end I tried here and found an answer similar but it doesn't satisfy at all my question

Here answers how to write some text by writing it in a constant, but it doesn't allows you to whrite by console

Im so novice in programming world so I apologize if it's too ordinary my question. In addition, I apollogize about my english skills too.

Thanks in advance.

  #include "modificator.h"

    int main(void) {
        editFile();
        return 0;
    }

    void editFile() {
        FILE* f;
        Cadena cad, res;  //"Cadena is an array of char"

        printf("Write the access rout to file required: \n");
        scanf("%s", cad);

        f = fopen(cad, "w");

        if (f == NULL) {
            printf("Wrong opening file\n");
        }
        const char *text = scanf("%s", res);    
        fprintf(f, "Some text: %s\n", text);

        fclose(f);
    }

Solution

  • const char *text = scanf("%s", res);
    

    No, no, no. scanf() returns a value of int type

    int chk = scanf("%s", res); // beware buffer overflows
    if (chk == 1) {
        fprintf(f, "Some text: %s\n", res);
    }