我在结构中有一个数组。我正在从一个文件读到一个字符串。我使用strtok获取前几个字符,我想将其余部分传递给结构,最终传递给一个线程。我收到以下错误:
从类型char[1024]
分配类型char *
时,不兼容的类型
参考下面的行和评论。它可能与我如何复制字符数组有关,但我不确定更好的方法。
#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 :(得分: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
答案 1 :(得分:0)
您需要将缓冲区中的字符复制到pcontents.pline中(假设pcontents
为PeriodicThreadContents
)。
答案 2 :(得分:-1)
strcpy(pcontents.pline, strtok(NULL, " "));