使用inotify向文件添加一段注释

本文介绍了一种在Ubuntu系统中使用inotify监控目录的方法,当新建文件时自动写入注释。通过C++代码实现,适用于Ubuntu18.04环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 需求简介:

在ubuntu系统上任意打开一个文件(vim,touch获取其它方式),该新建的文件都会被写入一段注释。

二 实现:

编译环境:ubuntu 18.04

实现方法:利用inotify监控目录这个特性,当在一个目录里新建文件时,可以read事件,从而获取文件名,然后调用c++ ofstream写入注释。

运行效果:

实现代码:

#include <stdio.h>  
#include <string.h>  
#include <stdlib.h>  
#include <sys/inotify.h>  
#include <unistd.h>  
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
static const int FILE_IN_CREATE_MASK = 256; 
static const char *COMMIT_STR = "/* \n\
 *@auth:hello world\n \
*@file:hello world\n \
*@license:hello world\n \
*@change story:hello world\n \
*------------------------------------\n\
*/";
const char *monitor_path = nullptr;
inline void write_commit(struct inotify_event *event) {
	if (FILE_IN_CREATE_MASK == event->mask) {
		if (event->len > 0 && !(event->mask & IN_ISDIR)) {
			char path[128] = "";
			const char *filename = event->name;
			snprintf(path, sizeof(path), "%s%s", monitor_path, filename);
			ofstream ofs(path);
			if (!ofs) {
				cerr << path << " can not be open...!" << endl;
				return;
			}
			ofs << COMMIT_STR << endl;
			ofs.close();
		}
	}
}
int main(int argc, char **argv) {
	char buf[BUFSIZ] = "";
	int len = 0;
	int nread = 0;
	struct inotify_event *event = nullptr;
	if (argc < 2) {
		fprintf(stderr, "%s path\n", argv[0]);
		return -1;

	}
	int fd = inotify_init();
	if (fd < 0) {
		fprintf(stderr, "inotify_init failed\n");
		return -1;
	}
	monitor_path = argv[1];
 	int wd = inotify_add_watch(fd, monitor_path, IN_CREATE);
	if (wd < 0) {
		fprintf(stderr, "inotify_add_watch %s failed\n", argv[1]);
		return -1;
	}
	int n = sizeof(buf) - 1;
	while ((len = read(fd, buf, n)) > 0) {
		nread = 0;
		while (len > 0) {
			event = (struct inotify_event *)&buf[nread];
			write_commit(event);
			nread = nread + sizeof(struct inotify_event) + event->len;
			len = len - sizeof(struct inotify_event) - event->len;
		}
	}
 
	return 0;
}

编译脚本:

g++ -std=c++17 -g -o Test main.cpp

注:不支持递归目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值