简体   繁体   中英

Cannot write full string to file

I need my program to append whole strings to my file. My code looks like this:

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

int main()
{
    char nazivDatoteke[128];
    printf("Unesite naziv datoteke koja ce se kreirati: ");
    scanf("%123s",nazivDatoteke);

    FILE *pokDatTestna = NULL;
    FILE *pokDatZavrsna = NULL;
    char nazDatZavrsna[] = "zavrsna.txt";
    char linija[100+1];
    char tekst[128];
    pokDatTestna = fopen(nazivDatoteke, "a");
    pokDatZavrsna = fopen(nazDatZavrsna, "a");

    if(pokDatTestna == NULL || pokDatZavrsna == NULL)
    {
        printf("Datoteke nije moguce otvoriti!");
        exit(EXIT_FAILURE);
    }

    do{
    printf("Unesite recenicu koja ce se upisati u datoteku: ");
    scanf("%s", tekst);
    if (strcmp("KRAJ",tekst) != 0){
        fprintf(pokDatTestna, "%s\n", tekst);
        }
    }while(strcmp("KRAJ",tekst) != 0);

    fclose(pokDatTestna);

    pokDatTestna = fopen(nazivDatoteke, "r");

    while(fscanf(pokDatTestna, "%100[^\n]%*c", linija) >= 0)
    {
        fprintf(pokDatZavrsna, "%s\n", linija);
    }

    fclose(pokDatTestna);
    fclose(pokDatZavrsna);

    return 0;
}

This works, but not for appending full strings. It appends them separately. So if I input "this is a test sentence", the file will read:

this
is
a
test
sentence

When I tried to use fgets or "%[^\\n]" in the scanf, it got stuck in an infinite loop and appended whitespaces to the file. I don't know what I'm doing wrong, as it works with scanf, but as soon as I use a method that doesn't stop scanning until newline, the program acts weird.

if you want to read whole lines of text, don't use scanf() with %s . That's for whitespace-separated strings.

Use fgets() , and check the return value, I/O can fail:

while(fgets(tekst, sizeof tekst, stdin) != NULL &&
      strncmp(tekst, "KRAJ\n", 5) != 0)
{
}

This is a common problem. When you do

scanf("%123s",nazivDatoteke);
/* ... */
do {
    scanf("%[^\n]", tekst);
    /* ... */
} while (...);

You read a string into nazivDatoteke , but there is still a newline in the input buffer. When you try to scanf("%[^\\n]") , you get an empty line, because of this newline.

You can avoid this by skipping whitespace first. This can be done by prefixing the format string with a space

    scanf(" %[^\n]", tekst);

Now scanf reads the remaining and any leading whitespace and then consumes the rest of the line into tekst .

I think the problem is in this line:

while(fscanf(pokDatTestna, "%100[^\\n]%*c", linija) >= 0)

Replace it with:

while(fscanf(pokDatTestna, "%100[^\\n]%s", linija) >= 0)

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