c - c 中的两个流相互干扰

标签 c file-io stream

以下代码为我提供了一个其中包含“s”的文件。

main () {
    FILE *ptr_TextOut;
    char character;

    // Open TextOut
    ptr_TextOut=fopen("/Users/jonathanclark/Software Projects/C/Baffle/TextOut","w");
    if (!ptr_TextOut)
    {
        printf("Unable to open TextOut!");
        return 1;
    }

    character = 's';

    fputs(&character, ptr_TextOut);
    fclose(ptr_TextOut);

    return 0;
}

但是,当打开第二个流(如以下代码所示)时,我在文件中得到“sË–‚vˇ”。

main () {
    FILE *ptr_TextOut;
    FILE *ptr_CodeIn;
    char character;

    // Open TextOut
    ptr_TextOut=fopen("/Users/jonathanclark/Software Projects/C/Baffle/TextOut","w");
    if (!ptr_TextOut)
    {
        printf("Unable to open TextOut!");
        return 1;
    }

    // Open CodeIn
    ptr_CodeIn=fopen("/Users/jonathanclark/Software Projects/C/Baffle/CodeIn","r");
    if (!ptr_CodeIn)
    {
        printf("Unable to open CodeIn!");
        return 1;
    }

    character = 's';

    fputs(&character, ptr_TextOut);
    fclose(ptr_TextOut);
    fclose(ptr_CodeIn);

    return 0;
}

我一定不能同时打开两个流吗?或者我的代码中是否存在其他错误?在这两种情况下,我预计文件 TextOut 中都会有一个“s”。如果相关的话,我正在 MAC 上运行我的代码。我尝试在再次运行之前删除文件 TextOut 的早期版本,但得到相同的结果。感谢您的帮助。

最佳答案

fputs() 接收一个以 null 结尾的字符串,而不是与 fputc() 不同的字符。

In computer programming, a null-terminated string is a character string stored as an array containing the characters and terminated with a null character ('\0', called NUL in ASCII).

您将一个指向字符的指针作为参数,该参数没有 null 来终止它,这会导致未定义的行为。

The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This terminating null-character is not copied to the stream.

char character = 'c'; 替换为 char* word = "c";。这将使用指向空终止字符串的指针,而不是 char 原语。

此外,您还需要将对 fputs() 的调用更改为:

fputs(word, ptr_TextOut); // No need to reference the input (&)

或者,只需使用fputc(character, ptr_TextOut);

解释你的输出

在执行程序的底层内存结构上,变量可能是一个挨着一个存储的。 因此,如果巧合的是,另一个变量的位置正好位于字符变量之后并且其中包含 null,那么它将有效地终止该字符串。 这可能发生在第一个程序中,但不会发生在第二个程序中。

关于c - c 中的两个流相互干扰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44005404/

相关文章:

c - 加载 DLL 库

java - 从请求正文中提取图像会导致图像损坏(Spring MVC)

Java - 在 JAR 文件中写入 txt

c# - 进行网络 I/O 时 Stream.Read 是否被缓冲?

c - 如何在c中的文本文件中获取空行?

python - 使用 C 和 Python 代码创建一个 Python 模块

c# - 删除文件前几个字节的最快方法

c# - 在 Stream Read 上实现超时属性

c - 如何让 LZO 处理文件流?

c - 如何设置相机的fps?