2014-02-15 74 views
0

我在结构中有一个数组。我正在从一个文件读取字符串。我使用strtok来获取前几个字符,并且我想将该行的其余部分传递到结构中,最终传递到一个线程中。分配给从类型char *C中的结构问题

参考下述与评论的线路类型char[1024]

不兼容的类型:我收到以下错误。这可能与我如何复制字符数组有关,但我不确定是否有更好的方法。

#include <stdio.h> 
#include <pthread.h> 
#include <stdlib.h> 
#include <linux/input.h> 
#include <string.h> 
#include <time.h> 
#include <unistd.h> 

typedef struct 
{ 
    int period; //stores the total period of the thread 
    int priority; // stores the priority 
    char pline[1024]; // stores entire line of text to be sorted in function. 
}PeriodicThreadContents; 

int main(int argc, char* argv[]) 
{ 
    //opening file, and testing for success 
    //file must be in test folder 
    FILE *fp; 
    fp = fopen("../test/Input.txt", "r"); 

    if (fp == NULL) 
    { 
     fprintf(stderr, "Can't open input file in.list!\n"); 
     exit(1); 
    } 

    char line[1024]; 

    fgets(line, sizeof(line), fp); 

    //getting first line of text, containing  
    char *task_count_read = strtok(line," /n"); 
    char *duration_read = strtok(NULL, " /n"); 

    //converting char's to integers 
    int task_count = atoi(task_count_read); 

    int i = 0; 

    PeriodicThreadContents pcontents; 




    printf("started threads \n"); 

    while (i < task_count) 
    { 
     fgets(line, sizeof (line), fp); 
     strtok(line," "); 

     if (line[0] == 'P') 
     { 
      char *period_read = strtok(NULL, " "); 
      pcontents.period = atoi(period_read);   
      printf("%d",pcontents.period); 
      printf("\n"); 

      char *priority_read = strtok(NULL, " "); 
      pcontents.priority = atoi(priority_read); 
      printf("%d",pcontents.priority); 
      printf("\n"); 

      printf("\n%s",line); 
      memcpy(&(pcontents.pline[0]),&line,1024); 
      printf("%s",pcontents.pline); 
     } 

    } 


    return 0; 
} 
+0

你可以使用像'的memcpy(&(pcontents.pline [0]),行[0],1024) '... – francis

+0

'pcontents'定义在哪里? – wildplasser

+0

试图修剪我的代码,让我编辑它。 – user3287789

回答

2

C无法像其他语言那样处理字符串。 C没有使用辅助功能没有字符串分配或比较。

为了在缓冲区拷贝一个字符串,你可以使用:

strcpy(pcontents.pline, line); 

甚至(有一个保证,你的字符串长度不超过1024字节):

memcpy(pcontents.pline, line, 1024); 
pcontents.pline[1023] = '\0'; 

对于其他字符串操作检查:http://www.gnu.org/software/libc/manual/html_node/String-and-Array-Utilities.html#String-and-Array-Utilities

+0

谢谢,让我试试看 – user3287789

0

您需要的字符从缓冲区拷贝到pcontents.pline(假设pcontentsPeriodicThreadContents)。

-1
strcpy(pcontents.pline, strtok(NULL, " ")); 
+0

downvote是什么原因? – BLUEPIXY