读取并打印
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFER_SIZE 1024
void print_file_lines(const char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
char buffer[BUFFER_SIZE];
while (fgets(buffer, BUFFER_SIZE, file) != NULL) {
printf("%s", buffer);
}
fclose(file);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
return EXIT_FAILURE;
}
const char *filename = argv[1];
while (1) {
print_file_lines(filename);
sleep(3);
}
return EXIT_SUCCESS;
}
写入
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define FILENAME "execution_count.txt"
int main() {
FILE *file = fopen(FILENAME, "a");
if (file == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
int count = 0;
while (1) {
time_t now = time(NULL);
char time_str[20];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now));
char buffer[100];
snprintf(buffer, sizeof(buffer), "[%s] Execution count: %d\n", time_str, count);
if (fputs(buffer, file) == EOF) {
perror("Error writing to file");
fclose(file);
return EXIT_FAILURE;
}
count++;
fclose(file);
sleep(5);
file = fopen(FILENAME, "a");
if (file == NULL) {
perror("Error reopening file");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
下面写入方式是无效的(需要用上边每次重新打开的方式写入)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define FILENAME "execution_count.txt"
#define MAX_COUNT 10
int main() {
FILE *file = fopen(FILENAME, "a");
if (file == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
int count = 0;
while (count < MAX_COUNT) {
time_t now = time(NULL);
char time_str[20];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now));
char buffer[100];
snprintf(buffer, sizeof(buffer), "[%s] Execution count: %d\n", time_str, count);
if (fputs(buffer, file) == EOF) {
perror("Error writing to file");
fclose(file);
return EXIT_FAILURE;
}
count++;
sleep(5);
}
fclose(file);
return EXIT_SUCCESS;
}