0
点赞
收藏
分享

微信扫一扫

深度学习500问——Chapter03:深度学习基础(3)

拾光的Shelly 03-22 17:31 阅读 2
linuxc语言

文章目录


在这里插入图片描述

1. 写文件

int main()
{
    FILE* fp = fopen("myfile", "w");
    if (!fp)
    {
        printf("fopen error!\n");
    }

    const char* msg = "hello world!\n";
    int count = 5;
    while (count--)
    {
        fwrite(msg, strlen(msg), 1, fp);
    }

    fclose(fp);

    return 0;
}

2. 读文件

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

int main()
{
    FILE* fp = fopen("myfile", "r");
    if (!fp)
    {
        printf("fopen error!\n");
    }

    char buf[1024];
    const char* msg = "hello world!\n";

    while (1)
    {
        // 注意返回值和参数
        ssize_t s = fread(buf, 1, strlen(msg), fp);
        if (s > 0)
        {
            buf[s] = 0;
            printf("%s", buf);
        }
        if (feof(fp))
        {
            break;
        }
    }
    fclose(fp);
    return 0;
}

3. 输出信息到显示器的几个方法

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

int main()
{
    const char* msg = "hello fwrite\n";
    fwrite(msg, strlen(msg), 1, stdout);

    printf("hello printf\n");

    fprintf(stdout, "hello fprintf\n");

    return 0;
}

4. stdin / stdout / stderr

  • C 默认会打开三个输入输出流,分别是 stdin, stdout, stderr
  • stdin :标准输入流,默认读取键盘的输入;
  • stdout :标准输出流,默认向显示器输出;
  • stderr :标准错误流,默认向显示器输出错误信息;
  • 仔细观察发现,这三个流的类型都是 FILE*

5. 打开文件的方式

r		Open text file for reading.
		打开文本文件进行阅读。
		The stream is positioned at the beginning of the file.
		流位于文件的开头。
	
r+ 		Open for reading and writing.
		打开(文件)进行阅读和写作。
		The stream is positioned at the beginning of the file.
		流位于文件的开头。
	
w 		Truncate file to zero length or create text file for writing.
		将文件缩短为零长度(清空文件)或创建用于写入的文本文件。
		The stream is positioned at the beginning of the file.
		流位于文件的开头。
	
w+		Open for reading and writing.
		打开(文件)进行阅读和写作。
		The file is created if it does not exist, otherwise it is truncated.
		如果文件不存在,则创建该文件,否则将其清空。
		The stream is positioned at the beginning of the file.
		流位于文件的开头。
	
a 		Open for appending (writing at end of file).
		打开用于追加(在文件末尾写入)。
		The file is created if it does not exist.
		如果文件不存在,则创建该文件。
		The stream is positioned at the end of the file.
		流位于文件的末尾。
	
a+ 		Open for reading and appending (writing at end of file).
		打开用于读取和追加(在文件末尾写入)。
		The file is created if it does not exist.
		如果文件不存在,则创建该文件。
		The initial file position for reading is at the beginning of the file,
		用于读取的初始文件位置是在文件的开头,
		but output is always appended to the end of the file.
		但是输出总是附加到文件的末尾。

END
举报

相关推荐

0 条评论