Why C program prints blank line to file?

JZ555

I have the following C code which writes words given to program to file called "command.txt". If word is "quit" program ends, else it prints the word and writes it to file. However, if the word is "file" it gets the first word on the first line of file by using function getstring() and continues to next loop iteration. This word is then used on this new round and the code goes straight to "else"-branch and should print out the word and write it to file again.

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


void getstring(char **p) {
    char string[100];
    char *word = NULL;
    FILE *file = fopen("command.txt", "r");
    fgets(string, 100, file);
    word = strtok(string," \n");
    p[0] = word;
    fclose(file);
}

void writetofile (char **strarr) {
    FILE *file = fopen("command.txt", "a");
    fprintf(file, "%s\n", strarr[0]);
    fclose(file);
}

int main(void) {

    char line[100];
    char *word = NULL;
    char *strarr[5];
    char **p = NULL;
    int flag = 0, i;

    while (1) {
        if (flag == 1) {
            flag = 0;
        }
        else {
            printf("Give string: ");
            fgets(line, 100, stdin);
            word = strtok(line," \n");
            strarr[0] = word;
        }

        if (strcmp(strarr[0], "quit") == 0) {
            break;
        }
        else if (strcmp(strarr[0], "file") == 0) {
            p = strarr;
            getstring(p);
            flag = 1;
            continue;
        }
        else {
            printf("Text: %s\n", strarr[0]);
            writetofile(strarr);
        }

        for (i=0; i<5; i++) {
            strarr[i] = NULL;
        }
    }   

    return 0;
}

The problem is this: if I type in "file" nothing is written to the file. For example, if I give the words "hello", "file" and "world" and then quit the program the printout looks like this:

Give string: hello
Text: hello
Give string: file
Text: hello
Give string: world
Text: world
Give string: quit

command.txt looks like this:

hello

world

So, there's an empty line where should be another "hello". Why is this? Am I missing something obvious here or is this because of the way pointers are used?

uesp

Once possible issue is that you are returning a pointer to a local variable in getstring():

void getstring(char **p) {
    char string[100];
    char *word = NULL;
    ...
    word = strtok(string," \n"); 
    p[0] = word;                 //word points into string[] which is a local
    ...
}

After your return from getstring() the local variable string[] is not longer valid and thus accessing p[0] later on is undefined behaviour.

To fix this either copy the word into a fixed buffer or allocate the memory for the return string.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Why does C program(to delete a line) delete the first character of my .txt file?

분류에서Dev

Add and number blank line above each line in a file

분류에서Dev

Adding line numbers in a file in C

분류에서Dev

Why is there an extra line in the file I am writing?

분류에서Dev

Why this Ansi C program does not give result?

분류에서Dev

Why does this C program crash? No bugs are reported

분류에서Dev

Why is this program not printing the input I provided? (C)

분류에서Dev

Spacing problem in Java program that prints tree as output

분류에서Dev

Why do the strings output using fprintf end up not being written to the output file if my program is terminated via CTRL-C?

분류에서Dev

how to replace every 6th ooccurrence blank space with new line from a file?

분류에서Dev

Why does Bash give "No such file or directory" for a program that's in my PATH?

분류에서Dev

Writing to a file prints integers to my IDLE shell

분류에서Dev

Why is my program only printing out every other char? C

분류에서Dev

In Java, how to create a simple program that prints the number of consonants and vowels in a phrase?

분류에서Dev

How to make the input file of my program start from the 3rd line?

분류에서Dev

How can I pass command line arguments to a program in a Windows batch file?

분류에서Dev

C program over-writing file contents in if statement

분류에서Dev

Printing to a file while conducting n simulations for a program (in C)

분류에서Dev

C++ program opens file corectly on Linux but not on Windows

분류에서Dev

Compiled c++ output file displays random character at end of program?

분류에서Dev

How to keep batch file running while C# program quit?

분류에서Dev

How to get wifi password from gnome keyring file with a C program?

분류에서Dev

How to get wifi password from gnome keyring file with a C program?

분류에서Dev

on editing file upload field is blank

분류에서Dev

error ./c.sh: line 24: [: too many arguments in shell program

분류에서Dev

Why does this program loop?

분류에서Dev

C: Write to a specific line in the text file without searching

분류에서Dev

How to convert a windows batch file into a signle line "cmd /c" command?

분류에서Dev

Writing to a file in C++ space acts as a new line

Related 관련 기사

  1. 1

    Why does C program(to delete a line) delete the first character of my .txt file?

  2. 2

    Add and number blank line above each line in a file

  3. 3

    Adding line numbers in a file in C

  4. 4

    Why is there an extra line in the file I am writing?

  5. 5

    Why this Ansi C program does not give result?

  6. 6

    Why does this C program crash? No bugs are reported

  7. 7

    Why is this program not printing the input I provided? (C)

  8. 8

    Spacing problem in Java program that prints tree as output

  9. 9

    Why do the strings output using fprintf end up not being written to the output file if my program is terminated via CTRL-C?

  10. 10

    how to replace every 6th ooccurrence blank space with new line from a file?

  11. 11

    Why does Bash give "No such file or directory" for a program that's in my PATH?

  12. 12

    Writing to a file prints integers to my IDLE shell

  13. 13

    Why is my program only printing out every other char? C

  14. 14

    In Java, how to create a simple program that prints the number of consonants and vowels in a phrase?

  15. 15

    How to make the input file of my program start from the 3rd line?

  16. 16

    How can I pass command line arguments to a program in a Windows batch file?

  17. 17

    C program over-writing file contents in if statement

  18. 18

    Printing to a file while conducting n simulations for a program (in C)

  19. 19

    C++ program opens file corectly on Linux but not on Windows

  20. 20

    Compiled c++ output file displays random character at end of program?

  21. 21

    How to keep batch file running while C# program quit?

  22. 22

    How to get wifi password from gnome keyring file with a C program?

  23. 23

    How to get wifi password from gnome keyring file with a C program?

  24. 24

    on editing file upload field is blank

  25. 25

    error ./c.sh: line 24: [: too many arguments in shell program

  26. 26

    Why does this program loop?

  27. 27

    C: Write to a specific line in the text file without searching

  28. 28

    How to convert a windows batch file into a signle line "cmd /c" command?

  29. 29

    Writing to a file in C++ space acts as a new line

뜨겁다태그

보관