如何从用户输入写入多个字符串到文件?

时间:2016-11-22 19:00:20

标签: c

所以我有这个C程序,我希望用户创建一个具有所选文件名的文件(工作正常),然后将内容写入所述文件,该文件不起作用。我当前的代码所做的只是从用户输入中只写一个单字符串(第一个),即使我想将所有文本保存到文件中。我怎样才能做到这一点?我整个下午都试图自己解决这个问题(使用EOF,fprintf等)无济于事。提前谢谢!

void createFile()
{
char userfilename[40];
char filecontent[1000];
FILE *filePointer;

printf("How do you want to name your file? ");
scanf("%s", &userfilename);
filePointer = fopen(userfilename, "w");

printf("Enter file content: ");
scanf("%s", &filecontent);
fputs(filecontent, filePointer);

fclose(filePointer);
printf("Successful.");
}

3 个答案:

答案 0 :(得分:0)

问题是scanfscanf在读取第一个空白字符后终止。请改用getline()

void createFile()
{
    char userfilename[40];
    char *filecontent;
    FILE *filePointer;
    size_t len = 0;     //For reading length of line
    ssize_t read;       //For number of characters read

    printf("How do you want to name your file? ");
    scanf("%s", &userfilename);
    filePointer = fopen(userfilename, "w");

    printf("Enter file content: ");
    while ((read = getline(&filecontent, &len, stdin)) != -1) {
        fprintf(filePointer, "%s", filecontent);
    }
    fclose(filePointer);
    printf("Successful.");
}

这应该有效。 阅读getline here

答案 1 :(得分:0)

您的代码无法正常工作的原因是您读取了一个字符串,然后将该字符串写入该文件,最后关闭该文件。

如果您想从控制台读取多行,您必须:

1)创建一个循环,从键盘读取并写入文件
2)保持在该循环中直到读取一些字符(通常是EOF)

你有几种方法可以做你想做的事。这是一个解决方案:

#include <stdio.h>

void createFile()
{
    char userfilename[40];
    char filecontent[1000];
    FILE *filePointer;

    printf("How do you want to name your file? ");
    scanf("%s", &userfilename);
    filePointer = fopen(userfilename, "w");

    printf("Enter file content: ");

// your may read from keyboard a char at a time and write it in the file

    char c;
    while ((c = getchar()) != EOF)
        fputc(c, filePointer);

// this is your error: read one line and write that line without loop
//    scanf("%s", &filecontent);
//    fputs(filecontent, filePointer);

    fclose(filePointer);
    printf("Successful.");
}

int main(int argc, char *argv[])
{
    createFile(); // call your function

    return(0);
}

当您按EOF(文件结束)

时,程序将终止

在Windows中EOF = CTRL + Z
在UNIX / Linux中EOF = CTRL + D

答案 2 :(得分:0)

可以使用while循环。考虑使用fgets来读取输入。输入exit时,此循环将退出。

void createFile()
{
    char userfilename[40];
    char filecontent[1000];
    FILE *filePointer;

    printf("How do you want to name your file? ");
    scanf("%s", userfilename);
    if ( ( filePointer = fopen(userfilename, "w")) != NULL) {
        printf("Enter file content(or exit): ");
        while ( ( fgets ( filecontent, sizeof ( filecontent), stdin))) {
            if ( strcmp ( filecontent, "exit\n") == 0) {
                break;
            }
            fputs(filecontent, filePointer);
        }
        fclose(filePointer);
        printf("Successful.");
    }
}