2014-02-15 72 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