C语言 如何读取结构中值

2wnc66cl  于 2023-02-11  发布在  其他
关注(0)|答案(2)|浏览(120)

我正在使用fread()读取文件。[read file only]编译时,编译器抛出一个"Segmentation fault(core dumped)"错误。
我写了这个代码。

type #include <string.h>
#include <stdio.h> 
#include <stdlib.h>

int twilio_send_functionapi(char *channel, char *status); // function declartion 

struct credentials
 {

 char *account_sid;
 char *auth_token;
 char *from_number;
 char *to_number;

 } c1;
    
int main(int argc, char *argv[])
{   

    FILE *fp;
    struct credentials input;
    fp = fopen("data.config", "r");
    if (fp == NULL)
    {
        printf("Error\n");
        return -1;
    }
    
    dentials.to_number = (char*)malloc(sizeof(char)*100);
    while(fread(&c1,sizeof(struct credentials),1 ,fp))
    fscanf(fp,"%s %s %s %s", c1.account_sid, c1.auth_token,c1.from_number, c1.to_number);   
    
    char *channel,*status;

    channel = argv[1];
    status =  argv[2];
    twilio_send_functionapi(channel,status); //function call

}

不知道我哪里错了。这里是. conf文件,需要阅读

account_sid : AC40cfb4f3e98b55b13a9b93527683171e
auth_token  : 5f6906d7847ad1fc1fc1170ab60e40fd
from_number : 15867854760
to_number   : 1212321123
qjp7pelc

qjp7pelc1#

使用fgets()代替fread()fscanf()将文件的一行读入 string

//               123456789 123456789 123456789 123456789 
//account_sid :  AC40cfb4f3e98b55b13a9b93527683171e

#define SID_LEN 34

struct credentials {
  char account_sid[SID_LEN + 1];  // Use array here, not pointer.
  // ... omitted for  brevity
 } c1;

#define LINE_SIZE 100
char line[LINE_SIZE];
if (fgets(line, sizeof line, fp)) {
  if (sscanf(line, "account_sid : %34s", c1.account_sid) == 1) {
    ; // Success
  } else {
    ; // Failed
  }

对其他c1成员'继续进行类似操作。

disho6za

disho6za2#

谢谢大家我解决了我的问题。

char credential[4][100] ;
int main()
{
    FILE *fp;
     fp = fopen("data.config", "r");
if (fp == NULL)
{
    printf("Error\n");
    return -1;
}
printf("File is opened\n"); 
     if ((fscanf(fp,"account_sid-%s\n",credential[0])!= 1))
     {
     printf("error reading account_sid value\n");
     return -1;
     }
     fclose(fp);
      }

相关问题