我想使用sprintf生成txt文件

问题描述 投票:1回答:1

我该如何解决这个问题?

我想使用系统功能获取信息,并将其制作为文本文件。我不知道如何获取值并在其他函数中使用它们。

此外:使用sprintf将结果用作值是否正确?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <time.h>
#include <string.h>

char date;
char cpu_rate;
char mem_rate;
char value[500];

void printSystem()
{
    date = system("date");
    cpu_rate = system("top  -bn1| grep -Po '[0-9.]+ id'|head -n1|awk '{print sprintf(\"cpu usage: %.2f%\",100-$1)}'");
    mem_rate = system("top -bn1|grep \"KiB Mem\"| awk '{print sprintf(\"memory usage: %.2f%\",$8/$4*100)}'");
}

char strMK(){
    char* date;
    char* cpu_rate;
    char* mem_rate;

    printSystem();

    sprintf(value, date, cpu_rate, mem_rate);
    printf("%s\n",value);
}

void main(){
    FILE* fp = NULL;

    fp = fopen("mk.txt","w");

    if( fp == NULL)
    {
        printf("FILE OPEN ERROR");
        exit(0);
    }

    fprintf(fp, "%s\n",value);

    fclose(fp);
}
c linux string printf
1个回答
0
投票

您可以将系统功能中命令的输出重定向到文件。例如,

system ("command > file1");

如果愿意,您可以在程序中读取此文件。使用这种方法,您的程序将成为,

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <time.h>
#include <string.h>

char date;
char cpu_rate;
char mem_rate;
char value[500];

void printSystem()
{
    date = system("date > x");
    cpu_rate = system("top  -bn1| grep -Po '[0-9.]+ id'|head -n1|awk '{print sprintf(\"cpu usage: %.2f%\",100-$1)}' > y");
    mem_rate = system("top -bn1|grep \"KiB Mem\"| awk '{print sprintf(\"memory usage: %.2f%\",$8/$4*100)}' > z");
}

char strMK(){
    char* date;
    char* cpu_rate;
    char* mem_rate;

    printSystem();

/*    sprintf(value, date, cpu_rate, mem_rate);
    printf("%s\n",value);  */
}

void main(){
    FILE* fp = NULL;

    fp = fopen("mk.txt","w");

    if( fp == NULL)
    {
        printf("FILE OPEN ERROR");
        exit(0);
    }

    strMK ();
    // fprintf(fp, "%s\n",value);

    fclose(fp);
}

它执行为,

$ gcc try.c -o try
$ ./try
$ cat x
Mon May 18 17:15:31 IST 2020
$ cat y
cpu usage: 16.10%
$ cat z
memory usage: 19.24%
© www.soinside.com 2019 - 2024. All rights reserved.