用C语言写一个每秒向test.txt文件中写1M随机数据的程序
时间: 2023-02-19 19:15:08 浏览: 81
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w");
if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
int i;
time_t start_time = time(NULL);
while (time(NULL) - start_time < 1)
{
for (i = 0; i < 1000000; i++)
{
int x = rand();
fprintf(fp, "%d\n", x);
}
}
fclose(fp);
return 0;
}
相关问题
使用C语言写一个程序向一个已有内容的txt文件中追加行
可以使用C语言中的文件操作函数来实现向已有内容txt文件中追加行的功能。具体代码如下:
```c
#include <stdio.h>
int main() {
FILE *fp;
line[100];
//开文件,在文件末尾追加
fp = fopen("test.txt", "a+");
if (fp == NULL) {
printf("打开文件失败\n");
return 1;
}
// 输入需要追加的行
printf("请输入要追加的行(不超过100个字符):\n");
fgets(line, 100, stdin);
// 写入到文件
fputs(line, fp);
// 关闭文件
fclose(fp);
printf("已经将行追加到文件中\n");
return 0;
}
```
在这个程序中,首先使用文件操作函数`fopen()`打开一个已有的txt文件,并以追加写入的方式打开。然后从用户输入中获取需要追加的行,并使用`fputs()`函数将其写入到文件中。最后,关闭文件并输出提示信息。
linux用c语言编程读写一个文件 test.txt,每隔 1 秒向文件中写入一行数据,该程序应该无限循环,直到按 Ctrl-C 中断程序。下次再启动程序写文件时可以追加到原文件之后,并 且序号能够接续上次的序号,
好的,我来回答你的问题。下面是一个示例代码,可以实现你所需的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#define FILENAME "test.txt"
int main()
{
int fd;
int i = 0;
char buf[256];
time_t t;
struct tm *tm;
signal(SIGINT, SIG_IGN); // 忽略 Ctrl-C 信号
while (1)
{
if ((fd = open(FILENAME, O_WRONLY | O_CREAT | O_APPEND, 0644)) < 0) // 打开文件,若文件不存在则创建
{
perror("open");
exit(1);
}
t = time(NULL);
tm = localtime(&t);
sprintf(buf, "%d %04d-%02d-%02d %02d:%02d:%02d\n", ++i, tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); // 按要求格式化数据
if (write(fd, buf, strlen(buf)) < 0) // 写数据
{
perror("write");
exit(1);
}
close(fd); // 关闭文件
sleep(1); // 等待 1 秒
}
return 0;
}
```
在这个程序中,我们使用了 `open()` 函数打开文件,并使用了 `O_WRONLY`、`O_CREAT`、`O_APPEND` 参数来指定打开文件的模式。其中,`O_WRONLY` 表示只写模式,`O_CREAT` 表示如果文件不存在则创建,`O_APPEND` 表示在文件末尾追加数据。文件权限使用了 `0644`,表示文件所有者有读写权限,其他用户只有读权限。
我们使用了 `time()` 函数和 `localtime()` 函数获取当前时间,并使用了 `sprintf()` 函数将数据按要求格式化。然后使用 `write()` 函数将数据写入文件中,最后使用 `close()` 函数关闭文件。
程序使用了一个无限循环,每次循环都会打开文件、写入数据、关闭文件,并等待 1 秒。如果程序接收到了 Ctrl-C 信号,会忽略该信号,继续循环。这里没有进行错误处理,你可以根据需要进行修改。
当下次再次启动程序时,会追加到原文件之后,并且序号能够接续上次的序号。