简体   繁体   中英

Program crash when try to write into a file using a function by reference C

Well I have a problem using a function to write a string into a txt file, I just can't see why I can't print the string, when the program is in the function it just stop working. This is the code creating a function passing the value by reference of the file and it works perfectly:

void saveTXT(FILE** txt,char *string)
{
    fputs(string,*txt);
}
int main()
{
    FILE * doc;
    char string [10], singleline[50];
    printf("Write the name of the file: \n");
    scanf("%s",string);
    fflush(stdin);
    printf("Write the string to save into the file:\n");
    scanf("%[^\n]",singleline);
    doc = fopen(string,"w");
    saveTXT(&doc,singleline);
    fclose(doc);
    return 0;
}

But when I go back to my project that has the same logic the program just closes:

void saveTXT(FILE** txt,node* n)
{
  char buffer[100];
  
  if(n == NULL)
    fprintf(*txt,"*\n");
  else
  {
    strcat(strcpy(buffer,n->data),"\n");
    fflush(stdin);
    printf("This is the string to be saved: %s\n",buffer);
    fputs(buffer,*txt); //Problem
    saveTXT(&(*txt),n->right);
    saveTXT(&(*txt),n->left);
  }
}

I made sure to open the file before and close it later, what I print is the string to be saved in the file, it shows the string and then crash, I just don't know why that happens.

  1. There is no point in using double pointers here.
  2. stdin cannot be flushed.
  3. &(*txt) == txt

I think you struggle to understand what double pointers are for. You use them if you want to change the original pointer (single star one).

An example - the pointer fi will be modified in the function weirdopen :

void weirdopen(FILE **f, const char *filename)
{
    *f = fopen(filename, "r");
}

void myread(FILE *f, char *str, const size_t size)
{
    fgets(str, size, f);
}

int main(void)
{
    FILE *fi;
    char str[100];
    weirdopen(&fi, "test.txt");
    myread(fi, str, 100);

    fclose(fi);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM