我有一个大约2500行的数据文件。每行包含5个参数。我宣布了一个常规方面的支持。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<stdbool.h>
char *copy_string(const char *str) {
char *s = malloc(strlen(str) + 1);
if (s) strcpy(s, str); else {perror("malloc"); exit(1);}
return s;
}
void func(char **arr, char *w)
{
int i = 0, j = 0, k = 0;
char temp[100];
for (i = 0; i < 100; i++)
{
if (w[i] == '\0' || w[i] == '\n')
{
temp[j] = '\0';
arr[k] = copy_string(temp);
arr[k+1] = NULL;
break;
}
if (w[i] == ' ')
{
temp[j] = '\0';
arr[k] = copy_string(temp);
k++;
j = 0;
}
else
{
temp[j] = w[i];
j++;
}
}
}
int main(void)
{
char *n = "/bin/ls";
char *arr[10] = {NULL};
char p[100] = {0};
char *w = "ls -l";
int i = 0;
//printf("bilal-hassan-qadri $ >>");
fgets(p, 100, stdin);
w = p;
arr[2] = NULL;
bool found = false;
for (i = 0; w[i] != '\0'; i++)
{
if (w[i] == ' ')
{
found=true;
func(arr,w);
break;
}
}
if (!found)
arr[0] = w;
int status;
int id = fork();
if (id == 0)
{
if (execv(n,arr) < 0)
{
printf("invalid commandn");
}
else
{
printf("ninvalid command");
}
}
else
{
wait(&status);
for (i = 0; arr[i] != NULL; i++) free(arr[i]);
}
return 0;
}
我留出内存将文件的每一行读入一个结构数组。
typedef struct data
{
char date[9];
char time[3];
float price;
float NAV;
float percent_change;
} _data ;
void readfile(int *j, struct data *input);
void readfile(int *j,struct data *input)
并阅读文件。
input = calloc(days_of_data,sizeof(*input));
for (i = 0; i< days_of_data; i++)
input[i] = *(_data*)calloc(1,sizeof(_data));
这很有效。现在我想将结构发送到主程序。
while(fgets(line, 75, fp) != NULL)
{
date = strtok(line,",");
strcpy(input[i].date,date);
time = strtok(NULL,",");
strcpy(input[i].time, time);
price = strtok(NULL,",");
input[i].price = atof(price);
NAV = strtok(NULL,",");
input[i].NAV = atof(NAV);
percent_change = strtok(NULL,",");
input[i].percent_change = atof(percent_change);
i--;
}
这会在print语句中编译但崩溃。
答案 0 :(得分:1)
您必须使用返回值
void readfile(int *j, struct data **input_out) {
struct data *input;
/* read the data */
*input_out = input;
}
int main(int argc, const char * argv[]) {
struct data *input;
readfile(&j, &input);
printf("%f\n",input[0].percent_change);
}
或指针
package main
import (
"fmt"
"reflect"
)
type TT struct {
Foo int
}
type II interface {
Bar(int) (int, error)
}
type SS struct {
F1 TT
F2 II
}
func main() {
var rr SS
value := reflect.ValueOf(rr)
for ii := 0; ii < value.NumField(); ii++ {
fv := value.Field(ii)
xv := fv.Interface()
switch vv := xv.(type) {
default:
fmt.Printf("??: vv=%T,%v\n", vv, vv)
case TT:
fmt.Printf("TT: vv=%T,%v\n", vv, vv)
case II:
fmt.Printf("II: vv=%T,%v\n", vv, vv)
}
}
}
将数据传递给调用者。