Munna Tripathi
Munna Tripathi

Reputation: 105

How to write something in a existing .txt file with c program?

I am trying to write "File opened" in a existing test.txt file with C program. But I must not create a test.txt file with the program. I have to write with in a existing file.

I tried but can't.

Here is my code:

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

int main() {
    char sentence[1000] = "File opened";
    fopen("test.txt", "w");
    fprintf("%s", sentence);
    fclose();
    return 0;
}

The error showing me is:

error: too few arguments to function 'fclose'

How can I do that? Please help me.

Upvotes: 0

Views: 93

Answers (1)

Nickolas Kwiatkowski
Nickolas Kwiatkowski

Reputation: 58

In future recommend that you do some searching for either existing questions that people have asked or some research. ie look up the manual or spec for fopen: https://man7.org/linux/man-pages/man3/fopen.3.html

Especially since your code doesn't compiled as it has errors, with the fopen, fprintf and fclose all missing arguments or assignment variables. Reading those errors and the compiler messages would have guided you to the solution. This is what it would look like with those fixed and the "w+" option used:

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

int main() {
    char sentence[1000] = "File opened";
    FILE *file = fopen("test.txt", "w+");
    fprintf( file, "%s", sentence);
    fclose( file );
    return 0;
}

This is a good tutorial if you want to know more: https://www.geeksforgeeks.org/basics-file-handling-c/

Upvotes: 2

Related Questions