删除文件末尾的空新行 [英] Remove empty new line at the end of a file

查看:77
本文介绍了删除文件末尾的空新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,用于存储来自用户输入(stdin)的字符串

I have a file that's storing strings from the user's input (stdin)

但是有2种情况

如果我正常阅读文件,由于用户引入的最后一个字符串中的换行符,文件的末尾将有一个空行.

If I read it normally, my file will have an empty line at its end due to the newline from the last string the user introduced.

如果我从输入字符串中删除\n,则文件会将所有字符串存储在同一行中,这是不需要的.

If I remove the \n from the input string, the file stores all strings in the same line, which is not wanted.

如何简单地从文件末尾删除该换行符?

How can I simply remove that newline from the end of the file?

如果需要,我可以编辑并提供一些代码.

I can edit and provide some of my code if required.

假设我已经拥有的文件的最后一行是卡片"

Let's say the last line of a file I already have is "cards"

当光标在卡片"前面时,如果我按下向下箭头,则它不会继续到下一行,而在这种情况下,它可能会发生一次.

when the cursor is in front of "cards", if I press the down arrow it doesn't go on to the next line, while in this case it can happen once.

为了让我的代码正常运行,我不能让这种情况发生,

For my code to function perfectly I can't let that happen,

这是我所拥有的一个例子:

Here's an example of what I have:

f=fopen(somefile, "w");
do
{
    fgets(hobby, 50, stdin);
    fprintf(f, "%s", hobby)

} while(strcmp(hobby,"\n") != 0);

推荐答案

文件末尾的换行符 1 是最后一行的 part .可以删除它,但是会使最后一行不完整,这将破坏许多程序.例如,在此文件末尾串联另一个文件将导致最后一行与串联文件的第一行合并.

The newline character1 at the end of the file is part of the last line. Removing it is possible but makes the last line incomplete, which will break many programs. For example, concatenating another file at the end of this file will cause the last line to be merged with the first line of the concatenated file.

尤里·拉瓜迪亚(Yuri Laguardia)评论说,如果您以后在追加模式下重新打开此文件以写入更多行,则添加的第一个将在此最后一个不完整行的末尾串联.可能不是预期的行为.

A Yuri Laguardia commented, if you later reopen this file in append mode to write more lines, the first one added would be concatenated at the end of this last incomplete line. Probably not the intended behavior.

如果您不希望文件包含空行,请在将行写入文件之前检查用户输入:

If you do not want the file to contain empty lines, check user input before writing the line into the file:

void input_file_contents(FILE *fp) {
    char userinput[80];
    printf("enter file contents:\n");
    while (fgets(userinput, sizeof userinput, stdin)) {
        if (*userinput != '\n') {
            fputs(userinput, fp);
        }
    }
}

您的代码未在正确的位置测试终止:您在测试之前 之前写了空行.不要使用do / while循环:

Your code does not test for termination at the right place: you write the empty line before the test. Do not use a do / while loop:

f = fopen(somefile, "w");
if (f != NULL) {
    /* read lines until end of file or empty line */
    while (fgets(hobby, 50, stdin) != NULL && *hobby != '\n') {
        fputs(hobby, f);
    }
}


1 换行符实际上是旧系统上的一对字节<CR><LF>.


1 The newline character is actually a pair of bytes <CR><LF> on legacy systems.

这篇关于删除文件末尾的空新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆