将 Linux C Char 数组转换为 Int

发布于 2024-08-19 01:06:48 字数 1537 浏览 4 评论 0原文

需要一些关于这个的建议,因为我有点挣扎,无法弄清楚。

我有一个在 PC 上更新的文件,以指示系统运行及其运行时间。我正在编写一个非常简单的Linux控制台应用程序(最终将成为一个nagios插件)。它读取此文件并根据在文件中找到的内容进行响应。

我是 Linux 编程和使用 C 的新手,所以请耐心等待,如果您能解释任何答案,我们将不胜感激。

基本上我想将包含 5 个字符的 char 数组转换为整数,但是数组中的第 5 个字符始终是字母。所以从技术上讲,我想做的就是将数组中的前 4 个字符转换为整数......如何?我尝试了多种方法但没有成功,我的问题是目前我对这门语言没有很好的掌握,所以对它能做什么和不能做什么没有真正的想法。

这是我的程序的来源。

基本上,buf 数组将保存从文件中获取的字符串,该字符串看起来类似于

3455Y(数字是随机的,但始终为 4 个字符长)。

抱歉,代码格式很差,但我无法得到这个愚蠢的窗口,无论是出于爱还是金钱,都无法正确格式化它......

include <fcntl.h>
include <unistd.h>
include <stdio.h>
include <stdlib.h>
include <time.h>
include <string.h>

define COPYMODE 0644

int main(int argc, char *argv[])  
{
  int  i, nRead, fd;
  int  source;
  int  STATE_OK = 0;
  int  STATE_WARNING  = 1;
  int  STATE_CRITICAL = 2;
  int  STATE_UNKNOWN  = 3;
  int  system_paused  = 0; 

  char buf[5]; 
  int  testnumber;

  if((fd = open(argv[1], O_RDONLY)) == -1)
    {
      printf("failed open : %s", argv[1]);
      return STATE_UNKNOWN;
    }
      else
    {
      nRead = read(fd, buf, 5);
    }

  close(source);

  if (buf[4] == 'P')
    {
      printf("Software Paused");
      return STATE_WARNING;
    }
      else
    {
      return STATE_OK;
    }
    time_t ltime; /* calendar time */  
    struct tm *Tm;
    ltime=time(NULL); /* get current cal time */  
    Tm=localtime(&ltime);


    int test;
    test = Tm->tm_hour + Tm->tm_min;
    printf("%d", test);

    printf("%d", strtoi(buf));

}

need some advice on this one as im struggling abit and cannot figure it out.

i have a file that gets updated on a PC to indicate a system ran and what time it ran. i am writing a very simple linux console app (will eventually be a nagios plugin). that reads this file and responds depending on what it found within the file.

i am a total newbie to programming on Linux and using C so please be patient and if you would explain any answers it would really be appreciated.

basically i want to convert a char array containing 5 characters into an integer, however the 5th char in the array is always a letter. so technically all i want to-do is convert the first 4 chars in the array to a integer... how?? ive tried multiple ways with no success, my problem is that presently i do not have a good grasp of the language so have no real ideas on what it can and cannot do.

here is the source to my program.

basically the buf array will be holding a string taken from the file that will look something like this

3455Y (the number will be random but always 4 chars long).

Sorry for the poor formatting of the code, but i cannot get this stupid window for love nor money to format it correctly....

include <fcntl.h>
include <unistd.h>
include <stdio.h>
include <stdlib.h>
include <time.h>
include <string.h>

define COPYMODE 0644

int main(int argc, char *argv[])  
{
  int  i, nRead, fd;
  int  source;
  int  STATE_OK = 0;
  int  STATE_WARNING  = 1;
  int  STATE_CRITICAL = 2;
  int  STATE_UNKNOWN  = 3;
  int  system_paused  = 0; 

  char buf[5]; 
  int  testnumber;

  if((fd = open(argv[1], O_RDONLY)) == -1)
    {
      printf("failed open : %s", argv[1]);
      return STATE_UNKNOWN;
    }
      else
    {
      nRead = read(fd, buf, 5);
    }

  close(source);

  if (buf[4] == 'P')
    {
      printf("Software Paused");
      return STATE_WARNING;
    }
      else
    {
      return STATE_OK;
    }
    time_t ltime; /* calendar time */  
    struct tm *Tm;
    ltime=time(NULL); /* get current cal time */  
    Tm=localtime(<ime);


    int test;
    test = Tm->tm_hour + Tm->tm_min;
    printf("%d", test);

    printf("%d", strtoi(buf));

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

还如梦归 2024-08-26 01:06:49

您可以使用 atoi

atoi 需要一个 char * 参数并返回一个 int。
如果字符串为空,或者第一个字符不是数字或减号,则 atoi 返回 0。如果 atoi 遇到非数字字符,则返回截至该点形成的数字

int num = atoi(buf);

You can use atoi

atoi requires one char * argument and returns an int.
If the string is empty, or first character isn't a number or a minus sign, then atoi returns 0.If atoi encounters a non-number character, it returns the number formed up until that point

int num = atoi(buf);
秉烛思 2024-08-26 01:06:49

如果要将字符串的前四个字符转换为整数,请执行以下操作:

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>

uint8_t convertFirstFourChars(char * str, uint32_t *value){
  char tmp[5] = {0};
  strncpy((char *) tmp, str, 4);
  *value = strtoul(tmp);
  return errno;
}

然后像这样调用/测试此函数

#include <stdint.h>
#include <stdio.h>

int main(int argc, char **argv){

  char test1[5] = "1234A";
  char test2[5] = "ABCDE";

  uint32_t val = 0;
  if(convertFirstFourChars((char *) test1, &val) == 0){
    printf("conversion of %s succeeded, value = %ld\n", test1, val);
  }
  else{
    printf("conversion of %s failed!\n", test1);
  }

  if(convertFirstFourChars((char *) test2, &val) == 0){
    printf("conversion succeeded of %s, value = %ld\n", test2, val);
  }
  else{
    printf("conversion of %s failed!\n", test2);
  }

  return 0;
}

FWIW,不要使用 atoi(...) 因为它会转换任何字符串为整数,无论​​其作为数字的有效性如何。 atoi("foo") === 0

if you want to convert the first four characters of a string to an integer do this:

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>

uint8_t convertFirstFourChars(char * str, uint32_t *value){
  char tmp[5] = {0};
  strncpy((char *) tmp, str, 4);
  *value = strtoul(tmp);
  return errno;
}

then call / test this function like this

#include <stdint.h>
#include <stdio.h>

int main(int argc, char **argv){

  char test1[5] = "1234A";
  char test2[5] = "ABCDE";

  uint32_t val = 0;
  if(convertFirstFourChars((char *) test1, &val) == 0){
    printf("conversion of %s succeeded, value = %ld\n", test1, val);
  }
  else{
    printf("conversion of %s failed!\n", test1);
  }

  if(convertFirstFourChars((char *) test2, &val) == 0){
    printf("conversion succeeded of %s, value = %ld\n", test2, val);
  }
  else{
    printf("conversion of %s failed!\n", test2);
  }

  return 0;
}

FWIW, don't use atoi(...) because it converts any string to an integer regardless of its validity as a number. atoi("foo") === 0.

心的憧憬 2024-08-26 01:06:49

这是我能够从格式中恢复的尽可能多的代码:
<代码>

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>

#define COPYMODE 0644

int main(int argc, char *argv[]) { int i、nRead、fd; int 源; int STATE_OK = 0; int STATE_WARNING = 1; int STATE_CRITICAL = 2; int STATE_UNKNOWN = 3; int 系统暂停 = 0;

字符缓冲区[5]; int 测试编号;

if((fd = open(argv[1], O_RDONLY)) == -1) { printf("打开失败:%s", argv[1]); 返回STATE_UNKNOWN; } 别的 { nRead = 读取(fd, buf, 5); } 关闭(源);

if (buf[4] == 'P') { printf("软件已暂停"); 返回STATE_WARNING; } 别的 { 返回STATE_OK; } time_t ltime; /* 日历时间 / 结构 tm Tm; ltime=时间(NULL); /获取当前校准时间*/ tm=当地时间(<ime);

内部测试; 测试 = Tm->tm_hour + Tm->tm_min; printf("%d", 测试); printf("%d", strtoi(buf)); }

这是执行您指定操作的版本:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>

#define COPYMODE 0644

int main(int argc, char *argv[]) { int i、nRead、fd; int 源; int STATE_OK = 0; int STATE_WARNING = 1; int STATE_CRITICAL = 2; int STATE_UNKNOWN = 3; int 系统暂停 = 0;

字符缓冲区[5]; int 测试编号;

if((fd = open(argv[1], O_RDONLY)) == -1) { printf("打开失败:%s", argv[1]); 返回STATE_UNKNOWN; } 别的 { nRead = 读取(fd, buf, 5); } 关闭(源);

if (buf[4] == 'P') { printf("软件已暂停"); 返回STATE_WARNING; }/* 别的 { 返回STATE_OK; buf[4] = 0; } */ time_t ltime; /* 日历时间 */ 结构 tm *Tm; ltime=时间(NULL); /* 获取当前校准时间 */ tm=当地时间(<ime);

内部测试; 测试 = Tm->tm_hour + Tm->tm_min; printf("%d\n", 测试); printf("%d\n", atoi(buf)); }

代码中最大的问题是每个分支中都有返回的 if 语句,确保 if 语句之后不会执行任何内容。

this is as much of your code as I was able to recover from the formatting:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>

#define COPYMODE 0644

int main(int argc, char *argv[]) { int i, nRead, fd; int source; int STATE_OK = 0; int STATE_WARNING = 1; int STATE_CRITICAL = 2; int STATE_UNKNOWN = 3; int system_paused = 0;

char buf[5]; int testnumber;

if((fd = open(argv[1], O_RDONLY)) == -1) { printf("failed open : %s", argv[1]); return STATE_UNKNOWN; } else { nRead = read(fd, buf, 5); } close(source);

if (buf[4] == 'P') { printf("Software Paused"); return STATE_WARNING; } else { return STATE_OK; } time_t ltime; /* calendar time / struct tm Tm; ltime=time(NULL); / get current cal time */ Tm=localtime(<ime);

int test; test = Tm->tm_hour + Tm->tm_min; printf("%d", test); printf("%d", strtoi(buf)); }

this is the version that does what you specified:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>

#define COPYMODE 0644

int main(int argc, char *argv[]) { int i, nRead, fd; int source; int STATE_OK = 0; int STATE_WARNING = 1; int STATE_CRITICAL = 2; int STATE_UNKNOWN = 3; int system_paused = 0;

char buf[5]; int testnumber;

if((fd = open(argv[1], O_RDONLY)) == -1) { printf("failed open : %s", argv[1]); return STATE_UNKNOWN; } else { nRead = read(fd, buf, 5); } close(source);

if (buf[4] == 'P') { printf("Software Paused"); return STATE_WARNING; }/* else { return STATE_OK; buf[4] = 0; } */ time_t ltime; /* calendar time */ struct tm *Tm; ltime=time(NULL); /* get current cal time */ Tm=localtime(<ime);

int test; test = Tm->tm_hour + Tm->tm_min; printf("%d\n", test); printf("%d\n", atoi(buf)); }

The biggest problem with your code was the if statement with the returns in each branch, insuring that nothing after the if statement was ever executed.

清风不识月 2024-08-26 01:06:48

您可以使用 sscanf 来完成这项工作:

int num = 0;
sscanf(buf, "%4d", &num);

然后 num 应该保存文件中该行的数字。

You can use sscanf to do the job:

int num = 0;
sscanf(buf, "%4d", &num);

Then num should hold the number from the line in the file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文