C语言文件操作

目的:读取txt文件内容,并逐行打印至控制台
用到的函数:fopen fgets fclose

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

void printCurrentTime() {
    time_t now;
    time(&now); // time() returns the current time of the system as a time_t value
    printf("Today is : %s", ctime(&now));
}

int main() {
    printCurrentTime();    
    
    char *filename = "F:\2020\Project2333\pattern.txt";
    //printf("filename : %s", filename);
    FILE *fp;
    fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("Could not open file : %s", filename);
        return EXIT_FAILURE;
    }
    
    char line[50];
    while (fgets(line, 50, fp) != NULL) {
        printf("%s", line);
    }    
    
    fclose(fp);
    return EXIT_SUCCESS;
}

TXT文件内容

                    .----.
                 _.'__    `. 
             .--(#)(##)---/#
           .' @          /###
           :         ,   #####
            `-..__.-' _.-###/  
                  `;_:    `"'
                .'"""""`. 
               /,  JOE  ,
              //  COOL!  \
              `-._______.-'
              ___`. | .'___ 
             (______|______)


输出结果

参考

C文件处理:https://fresh2refresh.com/c-programming/c-file-handling/
C打印当前时间:https://www.techiedelight.com/print-current-date-and-time-in-c/

原文地址:https://www.cnblogs.com/Todd-Qi/p/12555475.html