简体   繁体   English

将Linux C Char数组转换为Int

[英]Convert Linux C Char Array to Int

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. 我有一个文件,在PC上更新,以指示系统运行和运行的时间。 i am writing a very simple linux console app (will eventually be a nagios plugin). 我正在写一个非常简单的linux控制台应用程序(最终将成为一个nagios插件)。 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. 我是Linux上编程和使用C的全新手,所以请耐心等待,如果你能解释任何答案,我将非常感激。

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. 基本上我想将包含5个字符的char数组转换为整数,但数组中的第5个字符始终是一个字母。 so technically all i want to-do is convert the first 4 chars in the array to a integer... how?? 所以从技术上讲,我想要做的就是将数组中的前4个字符转换为整数...如何? 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 基本上buf数组将保存从文件中取出的字符串,看起来像这样

3455Y (the number will be random but always 4 chars long). 3455Y(数字将是随机的,但总是4个字符长)。

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(&ltime);


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

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

}

You can use sscanf to do the job: 您可以使用sscanf来完成这项工作:

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

Then num should hold the number from the line in the file. 然后num应该保存文件中该行的数字。

You can use atoi 你可以使用atoi

atoi requires one char * argument and returns an int. atoi需要一个char *参数并返回一个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 如果字符串为空,或者第一个字符不是数字或减号,则atoi返回0.如果atoi遇到非数字字符,则返回形成的数字直到该点

int num = atoi(buf);

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. FWIW,不要使用atoi(...)因为它将任何字符串转换为整数,无论​​其有效性如何。 atoi("foo") === 0 . atoi("foo") === 0

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(&ltime);

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(&ltime);

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. 你的代码最大的问题是if语句带有每个分支的返回值,确保if语句之后没有执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM