0
#include<stdio.h>
#include<stdlib.h>
void main(){
    FILE *fp;
    char str[20];
    fp=fopen("krishna.txt","a");
    if(fp==NULL)
        printf("File not exist");
        exit(1);
    printf("Enter the strings:");
    
    gets(str);
    fputs(str,fp);
    //fprintf(fp,"%s",str);
    printf("Successfully print");
    fclose(fp);
}

why it is not appending

i want this to append in my existing file name krishna

  • 1
    That code should not even show the `Enter the strings:` string because the program will end at `exit(1)` just above. Please give the exact behaviour of the code that you show. – Serge Ballesta Oct 26 '22 at 08:31
  • 1
    Welcome to SO. You should *never ever* use `gets`. It is considered so dangerous that is has been removed from the standard decades ago. Use `fgets` instead. – Gerhardh Oct 26 '22 at 08:38
  • 3
    Running your program in a debugger should be the very first step in your hunt for bugs. It should reveal immediately what's going wrong in your program. Hint: Your indentation does not reflect the logic of your program. – Gerhardh Oct 26 '22 at 08:39
  • Please [edit] and show the properly formatted **verbatim** input and output of your program as it appears in your console. – Jabberwocky Oct 26 '22 at 08:48
  • 3
    C is not python, you need braces { } for the if block. – CGi03 Oct 26 '22 at 08:53

1 Answers1

2

Use curly braces { } to surround multiple statements in a block.

Additionally, try using perror to better understand why things fail.

Do not use gets, please read: Why is the gets function so dangerous that it should not be used?

Use a proper signature for main: void main() is rarely correct. Use either int main(int argc, char **argv) if you want to use program arguments, or int main(void) if you do not.

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

int main(void)
{
    char str[128];
    FILE *fp = fopen("krishna.txt", "a");

    if (!fp) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    printf("Enter a line of text: ");

    if (fgets(str, sizeof str, stdin) && fputs(str, fp) > 0) {
        puts("Line appended to file.");
    } else {
        perror("fgets/fputs");
    }

    fclose(fp);
}
Oka
  • 23,367
  • 6
  • 42
  • 53