string.h 相关问题


标识符“字符串”未定义?

我收到错误:标识符“字符串”未定义。 但是,我包含了 string.h 并且在我的主文件中,一切正常。 代码: #pragma一次 #包括 #包括<


'string' 不命名类型;您指的是 'stdin' 吗?

我正在尝试编译一个引用我的“CardCreator.h”文件的 main.cpp 文件。当我尝试编译“main.cpp”文件时,它抛出错误 undefined reference to `CardCreator::


<string.h>和<strings.h&gt之间的区别。

我注意到(至少在Mac OS X上)同时存在一个 头部和一个 man 3字符串显示它们包含不同的函数。有什么原因吗?


如何从 scanf() 语句读取文本文件

我有一个基本的 C 程序,可以读取名为“inputFile.txt”的文本文件,但我想修改该程序以询问用户文件名,然后读取该文件。我已附上...


未定义函数 strcmp 但我包含了 string.h [关闭]

所以,我在 vscode 上遇到了这个问题。我在我的代码中包含了 string.h 但是当我编译它时它说: 这是我实现的代码: #包括 #包括 #包括 所以,我在 vscode 上遇到了这个问题。我在我的代码中包含了 string.h 但是当我编译它时它说: 这是我实现的代码: #include <stdio.h> #include <stdlib.h> #include <string.h> #include "item.h" #include "utilities.h" #define MAXLENGTH 50 void *getValue(item x) { char *a = x; return a; } int eq(item x, item y) { char *a, *b; a = x; b = y; return strcmp(a,b); //warning here } item input_item() { char *x; x = xmalloc(sizeof(char) * MAXLENGTH); gets(x); return x; } void output_item(item x) { char *a = x; printf("%s",a); } void removeItem(item x) { free(x); } 我尝试多次包含库,我尝试移动包含但警告仍然存在。 不只是这个程序有问题,我做的所有程序都有问题 Item.h 是一个头文件,其中包含 item.c 中所有函数的声明。 Item 是我在列表和堆栈中使用的通用类型。 Utilities.h 只包含函数 xmalloc 分配一个指针并控制它。 我尝试创建一个小程序(只有指令strcmp()),但错误仍然存在


C 中的链表:“‘struct’之前的预期表达式

我正在用 C 语言编写一个链表,作为我的第一个 C 作业,但我遇到了一个障碍。我需要另一双眼睛来帮助我发现我做错了什么。 #包括 #包括 我正在用 C 语言编写一个链表,作为我的第一个 C 作业,但我遇到了一个障碍。我需要另一双眼睛来帮助我发现我做错了什么。 #include <string.h> #include <stdio.h> #include <stdlib.h> struct Node { char *data; struct Node *next; }; struct Linked_List { struct Node *header; }; void insertAtBeginning(struct Linkedlist *LL, char ele[]) { struct Node new_node = malloc(sizeOf(struct Node)); //error occurs here } int main() { struct Node head; struct Linked_List LL; LL.header = &head; char string[] = "hello"; insertAtBeginning(LL, string); return 0; } 在指示的行上,我收到一条错误消息“‘struct’之前有预期的表达式”。 我对 C 很陌生,不知道是什么原因造成的。我的猜测是,这与滥用指针有关,但我看不出我哪里搞砸了。我将非常感谢任何和所有的建议。谢谢大家! sizeof运算符区分大小写,并且需要全部小写。


代码编译但打印意外的“-nan”

它应该接受文本并打印阅读级别,它似乎可以工作,除了它在接受文本输入后只打印“-nan”。 #包括 #包括 #包括 它应该接受文本并打印阅读级别,它似乎可以工作,除了它在接受文本输入后只打印“-nan”。 #include <cs50.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> int compute_Readability(string Text); int compute_Letters(string Text); int compute_words(string Text); int compute_sentences(string Text); float words; float letters; float sentences; float Grade; int main(void) { string Text = get_string("Text: "); compute_Readability(Text); if (Grade < 1) { printf("Before Grade 1\n"); } else if (Grade > 16) { printf("Grade 16+\n"); } else printf("Grade: %f\n" , (float) round (Grade)); } int compute_Letters(string Text) { for (int i = 0, len = strlen(Text); i < len; i++) if (isalpha(Text[i])) { letters++; } return letters; } int compute_words(string Text) { for (int i = 0, len = strlen(Text); i < len; i++) if (isblank(Text[i])) { words++; } return words +=1; } int compute_sentences(string Text) { for (int i = 0, len = strlen(Text); i < len; i++) if(Text[i] == '.' || Text[i] == '?' || Text[i] == '!') sentences++; return sentences; } int compute_Readability(string Text) { float avgletters = letters / words * 100; float avgsentences = sentences / words * 100; Grade = 0.0588 * avgletters - 0.296 * avgsentences - 15.8; return Grade; } 这是我的第一个编码项目之一,所以说实话,我不太确定发生了什么。我以前从未见过 -nan 所以我真的不知道它来自代码的哪一部分或者我可以做些什么来影响不同的输出。


使用malloc定义字符串地址

运行此代码时没有任何输出。我期望使用大写值写入文件,并将大写值打印到屏幕上。 #包括 #包括 运行此代码时没有任何输出。我期望使用大写值写入文件,并将大写值打印到屏幕上。 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main(int argc, const char * argv[]) { FILE *fP; char *str = "this is an example"; /* Im not sure if this line is right */ str = (char *)malloc(sizeof(char) * 100); fopen("4.txt", "w"); size_t length = strlen(str); for (size_t i = 0; i < length; i++) { /* This line fails */ fprintf(fP, "%c", toupper(*(str +i ))); printf("%c", toupper(*(str +i ))); } return 0; } 您正在运行 fopen() 而不返回 fp ,这只会打开文件流,但不会让它被 fp 引用,您需要将该行更改为 fp = fopen("4.txt" , "w"); 您也在 str 上运行 strlen() ,但由于您分配了内存但没有在其中存储任何内容(之前分配的字符串被覆盖),它将返回一个随机数( malloc() 给出了一个内存块而不清除以前的内存,因此,无论以前使用它的程序都将存储在其中),您都需要使用 strcpy() 将字符串设置到其中,如下所示 strcpy(str , "this is an example"); 如果解决了这两个问题,它应该可以运行。


在 C 中将结构写入 .txt 文件

我正在尝试将 .txt 文件中的数据读入结构数组,然后使用所述数组将其中一些数据写入另一个 .txt 文件。 我的代码: #define _CRT_SECURE_NO_WARNINGS #包括 我正在尝试将 .txt 文件中的数据读入结构数组,然后使用所述数组将其中一些数据写入另一个 .txt 文件。 我的代码: #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <ctype.h> #define MAX 5 // max array size //C:\\Users\\PATOX\\Desktop\\uczniowie.txt struct para { char name[15]; int grade; }; int read(FILE* file, struct para tab[], int m, int *k) { FILE* output; char path[80]; printf("Enter input file path: "); scanf_s("%s", path, 80); file = fopen(path, "r"); if (file == NULL) { printf("\nError opening input file\n"); return 1; } else { char path[80]; printf("Enter output file path: "); scanf_s("%s", path, 80); output = fopen(path, "w"); if (output == NULL) { printf("\nError opening output file\n"); return 1; } for (int i = 0; i < m; i++) { if (!feof(file)) { int index; char name[15]; int grade; fscanf(file, "%d %s %d", &index, name, &grade); strcpy(tab[i].name, name); tab[i].grade = grade; fwrite(&(tab[i]), sizeof(struct para), 1, output); (*k)++; } } } fclose(file); fclose(output); return 0; } void print_array(struct para tab[], int m) { for (int i = 0; i < m; i++) { printf("%s %d\n", tab[i].name, tab[i].grade); } } int main() { int k = 0; //data counter FILE* file; struct para tab[5]; read(&file, tab, MAX, &k); print_array(tab, k); return 0; } 当我检查输出的 .txt 文件时,数据在这里,但是只有 .name 按预期写入,第二项被写入为一些工件: 预期(输出.txt) Drozd 4 Jas 5 Tom 6 Bas 8 实际(输出.txt) (输出.txt) Drozd ÌÌÌÌÌÌÌÌÌÌ Jas ÌÌÌÌÌÌÌÌÌÌÌÌ Tom ÌÌÌÌÌÌÌÌÌÌÌÌ Bas ÌÌÌÌÌÌÌÌÌÌÌÌ


How to solve this issue Segment fault (core dumped)?

我正在尝试在 linux 中编写 C 程序。这是代码: 在“shell>”提示符下输入我的输入后,gcc 给我以下错误: #包括 #包括 我正在尝试在 linux 中编写 C 程序。这是代码: 在“shell>”提示符下输入我的输入后,gcc 给我以下错误: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/shm.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> void main() { int shm_fd; char read_buff[1024]; void *ptr = NULL; shm_fd = shm_open("hello_class",O_RDONLY, 0666); ptr = mmap(0,4096, PROT_READ, MAP_SHARED, shm_fd,0); printf("%s", (char*)ptr); shm_unlink("hello_class"); } 对于初学者,您需要在打开共享内存对象之前创建它。 通过 if/perror 添加一些基本的错误检查到原始代码: shm_fd = shm_open("/hello_class",O_RDONLY, 0666); if (shm_fd < 0) { perror("shm_open");exit(1);} 会产生错误:(来自perror函数) shm_open: No such file or directory 创建共享内存区域; shm_fd = shm_open("/hello_class",O_CREAT, 0666); // create shared memory 现在您将能够打开/读取它(通常是另一个进程)。即: 进程1:检查/创建/写入数据 进程2:检查/创建/等待/读取数据 查看 svipc(7) 了解更多细节。特别是像信号量这样的同步机制。 但是,在这种情况下,正如鲍勃提到的那样,在向内存中写入有意义的内容之前,内存区域中不会有任何可用的东西。 注意:来自 shm_open(3) 联机帮助页,名称应以 / 开头


找到最小的正整数,使数组中的整数互不相除

给定一个由 N 个正整数组成的数组 A。 找到最小的正整数 d, s.t。不存在整数对 (i,j)(1<=i 给定一个由 N 个正整数组成的数组 A。 找到最小的正整数 d, s.t。不存在整数对 (i,j)(1<=i 给定 N 个元素,并假设所有元素都是唯一的,差异的数量可以是: 第 N - 第 1 个,第 N - 第 2 个,...,第 N - (N-1) 个; 第 (N-1) 个 - 第一个,第 (N-1) 个 - 第二个,...,第 (N-1) 个 - 第 (N-2) 个; 第 (N-2) 个 - 第一个、第 (N-2) 个 - 第二个、第 (N-2) 个 - 第三个、...、第 (N-2) 个 - 第 (N-3) 个; . . . 第二名 - 第一名; 即总共 N(N-1)/2 个差异。 令整数数组称为:arr。 然后,有: int arr[N]; 我不知道如何以比暴力方式更好的方式解决这个问题,其中绝对存在 O(N^2) 时间复杂度。 但是,似乎更简单的方法是计算两个数字的 gcd,比如说取最小的整数 d = arr[0] 那么,是否可以递归计算 gcd(d, arr[i]), i=1,2,3,..., N-1。 但是,我什至不知道它是否正确。 ` #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int checked_atoi (const char *from) { char *endptr= NULL; long lval= strtol(from, &endptr, 10); if (*endptr) { fprintf(stderr, "invalid number '%s'\n", from); exit(12); } else if (lval<INT_MIN || lval>INT_MAX) { fprintf(stderr, "value '%ld' out of range\n", lval); exit(13); } return (int)lval; } int gcd(int a, int b, int c){ if (b==0) return a; printf("\n step: %d<> gcd : a: %d, b: %d", c++, a, b); return gcd(b, a%b, c); } int find_smallest_d(int *arr, int N){ int smallest_d = arr[0]; printf("\n find_smallest_d"); for (int i=1; i<N; i++){ smallest_d = gcd(smallest_d, arr[i], 1); } return smallest_d; } int main(int argc, char *argv[]){ int N=argc-1; printf("The size of array: %d", N); int arr[N]; for (int i=0; i<N; ++i) { arr[i]= checked_atoi(argv[i+1]); } printf("The %d values:", N); for (int i=0; i<N; ++i) { printf(" %d", arr[i]); } printf("\n"); int smallest_d = find_smallest_d(arr, N); printf("\n smallest value of d is: %d", smallest_d); } ` 得到的结果表明程序中逻辑的实现可能是错误的,如获取输入:12,23,34,45,56,67;答案1. 差异abs(arr[i]-arr[j])的唯一值是: ` 1. abs(12-23) = 11, 2. abs(12-34) = 22, 3. abs(12-45) = 33, 4. abs(12-56) = 44, 5. abs(12-67) = 55, ` 因此,gcd应该是11;虽然不清楚是否需要 gcd。 另外,答案应该是:10。 你的方法很有趣,但我发现你的逻辑有问题。让我澄清问题,然后引导您解决解决方案。 问题陈述要求最小的正整数 (d),使得 ( |A[i] - A[j]| ) 对于任何 (i, j) 对都不能被 (d) 整除。您应该计算数组中所有元素之间的差异,然后确定这些差异的 gcd,而不是直接计算整个数组的 gcd。这是因为,根据定义,如果 (d) 除以数组中的所有差值,则 ( |A[i] - A[j]| ) 将能被 (d) 整除。 所以,正确的算法是: 计算数组元素之间的所有差异。 计算这些差异的 gcd。 返回 gcd 作为答案。 以下是更正代码的方法: #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int checked_atoi (const char *from) { // [Your existing checked_atoi implementation] } int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b); } int find_smallest_d(int *arr, int N){ int smallest_d = abs(arr[1] - arr[0]); for (int i = 0; i < N; i++){ for (int j = i + 1; j < N; j++){ int diff = abs(arr[i] - arr[j]); smallest_d = gcd(smallest_d, diff); } } return smallest_d; } int main(int argc, char *argv[]){ // [Your existing main implementation] } 对于给定的输入:12、23、34、45、56、67,差异的 gcd 确实是 11。 但是,由于计算所有成对差异,这种方法仍然具有 (O(N^2)) 复杂度。根据问题的限制,这可能足够有效,也可能不够有效。


使用 malloc 为结构体分配空间

我正在尝试使用用户的输入作为大小动态地将内存分配给结构,但每次我这样做时都会出现错误。 我的结构如下: #包括 #包括 我正在尝试使用用户的输入作为大小将内存动态分配给结构,但每次我这样做时都会出现错误。 我的结构如下: #include <stdio.h> #include <stdlib.h> #include <string.h> // structure that holds the info for a phone record struct PHONE_RECORD { char name[50]; char birthday[12]; char phone[15]; } *phonebook; 动态分配的代码在这里: int num_space(){ int num_records; struct PHONE_RECORD *phonebook; printf("Enter num of records: "); scanf("%d", &num_records); phonebook = (struct PHONE_RECORD*) malloc(sizeof(struct PHONE_RECORD)*num_records); if (phonebook == NULL){ printf("Not enough memory.\n"); return 1; } free(phonebook); return num_records; } 代码允许用户输入一个数字,但随后给我一个错误并退出程序。该项目中还有其他部分,但我已经对它们进行了所有测试,它们可以毫无问题地工作,只有 malloc 部分不起作用。 供参考,这是我的主要内容: #include <stdio.h> #include <string.h> #include "mini4Bphone.c" extern void addRecord(); extern void findRecords(); extern void listRecords(); extern void loadCSV(); extern void saveCSV(); extern int num_space(); // dispaly the menu void menu() { int choice; num_space(); //display unitl user quits using while loop and execute whatever command user inputs while (1) { printf("Phonebook Menu: "); printf("(1) Add "); printf("(2) Find "); printf("(3) List "); printf("(4) Quit "); printf("> "); scanf("%d", &choice); switch (choice) { case 1: addRecord(); break; case 2: findRecord(); break; case 3: listRecords(); break; case 4: return; default: printf("Invalid choice.\n"); break; } } } // load tne csv,menu and save the csv after all wanted functions are complete, return 0 int main() { loadCSV(); menu(); saveCSV(); return 0; } 感谢您的宝贵意见! 我尝试在函数内部和外部使用 malloc 无济于事。它应该让用户输入一个数字,然后将空间分配给结构。但是,每次我尝试运行该程序时,都会出现一个错误。 局部变量struct PHONE_RECORD *phonebook;隐藏同名全局变量 num_space() 分配空间然后释放它。这是没有意义的。想必你想为全局变量分配空间: int num_space() { int num_records; printf("Enter num of records: "); scanf("%d", &num_records); phonebook = (struct PHONE_RECORD*) malloc(sizeof(struct PHONE_RECORD)*num_records); if (phonebook == NULL){ printf("Not enough memory.\n"); return 1; } return num_records; } 就您提供的信息而言,这可以解决您的段错误。 使用符号常量(NAME_LEN、BIRTHDAY_LEN、PHONE_LEN)代替魔法值(50、12、15)。 使用局部变量并传递他们操作所需的任何数据。这使您的代码更容易推理。 检查scanf()的返回值,否则你可能操作的是未初始化的数据。 喜欢使用变量而不是sizeof()的类型。它使类型更改更容易,重复代码更少。 在适当的时候优先使用无符号类型。 num_records < 0是什么意思? 0 应该是一个有效的选择吗? malloc(0) 是实现定义的,所以我在下面不允许它。 在menu()函数中为您的电话簿分配空间是没有意义的。将其移至main()。 不要从 malloc 投射void *。 (不固定)如果您不需要从 num_records 返回的 num_space() 值,则将返回类型更改为 void。如果这样做,请将返回值分配给变量。 (不固定)考虑在 char * 中使用 struct phonebook 而不是浪费的固定大小的字符串。它通常意味着每个成员的分配,但使用strdup().相当容易 最小化您的代码,以便您了解我们对您的期望: #include <stdio.h> #include <stdlib.h> #define NAME_LEN 50 #define BIRTHDAY_LEN 12 #define PHONE_LEN 15 struct phonebook { char name[NAME_LEN]; char birthday[BIRTHDAY_LEN]; char phone[PHONE_LEN]; }; size_t num_space(struct phonebook **phonebook) { size_t num_records; printf("Enter num of records: "); if(scanf("%zu", &num_records) != 1 || !num_records) { printf("scanf failed\n"); return 0; } *phonebook = malloc(sizeof **phonebook * num_records); if (!*phonebook) { printf("malloc failed\n"); return 0; } return num_records; } int main() { struct phonebook *phonebook = NULL; num_space(&phonebook); free(phonebook); }


即使添加了 #include <stdio.h>,popen 仍隐式声明

这是我的代码的一小段。 #包括 #包括 #包括 #包括 #包括 #包括 这是我的代码的一小段。 #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/types.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> ... FILE * pipe; ... pipe = popen ("ls /tmp -1", "r"); ... pclose(pipe); blarg.c:106: warning: implicit declaration of function ‘popen’ blarg.c:106: warning: assignment makes pointer from integer without a cast blarg.c:112: warning: implicit declaration of function ‘pclose’ blarg.c:118: warning: assignment makes pointer from integer without a cast 我真的不确定。我查了一下popen,它所需要的只是提供的stdio.h。缺少什么,或者是我的代码的其余部分有问题(我真的不想显示更多代码,因为它是一个作业)。 将 -std=c99 或 -std=c11 等替换为 -std=gnu99 或 -std=gnu11。 正如手册页所说: Feature Test Macro Requirements for glibc (see feature_test_macros(7)): popen(), pclose(): _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE 所以你应该在#define _BSD_SOURCEing #include之前stdio.h或其他之一。 我在MinGW中遇到了这个问题;在它的 stdio.h 中我发现: #ifndef NO_OLDNAMES _CRTIMP __cdecl __MINGW_NOTHROW FILE * popen (const char *, const char *); _CRTIMP __cdecl __MINGW_NOTHROW int pclose (FILE *); #endif 事实证明,我的 gcc 命令行上有 -DNO_OLDNAMES=1 来修复另一个我什至不记得的另一个源文件中的一些模糊问题。这是我的简单修复: #ifdef NO_OLDNAMES #undef NO_OLDNAMES #endif #include <stdio.h> 正如@Conrad Mayer 等其他人评论的那样。 简洁,只需添加 #define _POSIX_C_SOURCE 200809L // Define this before any includes #include <stdlib.h> ... rest of code ... 解释 popen() 函数是 POSIX 标准的一部分,其声明可能取决于正确定义的功能测试宏。这应该确保 popen() 的必要声明可用。 如果问题仍然存在,您可以尝试在包含标头之前定义 _GNU_SOURCE,因为 popen() 也是 GNU 扩展: #define _GNU_SOURCE #include <stdlib.h> ... 我将 popen 和 pclose 的原型放在代码的顶部。看来问题已经解决了。


在进程之间共享条件变量和互斥量:之前是否必须锁定互斥量?

我需要一些帮助来理解如何在 C 中使用条件变量来解决练习。这是一个小例子: #包括 #包括 #包括 我需要一些帮助来理解如何在 C 中使用条件变量来解决练习。这是一个小例子: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #define OKTOWRITE "/oktowrite" #define MESSAGE "/message" #define MUTEX "/lock" int main(int argc, char** argv) { pthread_cond_t* condition; pthread_mutex_t *mutex; char* message; int des_cond, des_msg, des_mutex; int mode = S_IRWXU | S_IRWXG; des_mutex = shm_open(MUTEX, O_CREAT | O_RDWR | O_TRUNC, mode); if (des_mutex < 0) { perror("failure on shm_open on des_mutex"); exit(1); } if (ftruncate(des_mutex, sizeof(pthread_mutex_t)) == -1) { perror("Error on ftruncate to sizeof pthread_cond_t\n"); exit(-1); } mutex = (pthread_mutex_t*) mmap(NULL, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, des_mutex, 0); if (mutex == MAP_FAILED ) { perror("Error on mmap on mutex\n"); exit(1); } pthread_mutex_init(mutex, NULL ); des_cond = shm_open(OKTOWRITE, O_CREAT | O_RDWR | O_TRUNC, mode); if (des_cond < 0) { perror("failure on shm_open on des_cond"); exit(1); } if (ftruncate(des_cond, sizeof(pthread_cond_t)) == -1) { perror("Error on ftruncate to sizeof pthread_cond_t\n"); exit(-1); } condition = (pthread_cond_t*) mmap(NULL, sizeof(pthread_cond_t), PROT_READ | PROT_WRITE, MAP_SHARED, des_cond, 0); if (condition == MAP_FAILED ) { perror("Error on mmap on condition\n"); exit(1); } pthread_cond_init(condition, NULL ); if (!fork()) { sleep(3); pthread_mutex_lock(mutex); pthread_cond_signal(condition); pthread_mutex_unlock(mutex); printf("son signaled\n"); exit(0); } else { printf("wait on condition\n"); pthread_mutex_lock(mutex); pthread_cond_wait(condition, mutex); pthread_mutex_unlock(mutex); printf("Signaled by son process, wake up\n"); pthread_mutex_destroy(mutex); pthread_cond_destroy(condition); shm_unlink(OKTOWRITE); shm_unlink(MESSAGE); shm_unlink(MUTEX); return 0; } } 问题是进程的父亲继续被锁定,即使在儿子发出信号之后也是如此。一切都在共享内存中(使用shm_open和mmap)所以两个进程的条件应该相同。 在调用 wait 或 signal 之前锁定互斥锁可能是我犯了一个错误吗? 编辑: 感谢所有帮助过我的人。这是标有关键部分的正确代码: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #define OKTOWRITE "/condwrite" #define MESSAGE "/msg" #define MUTEX "/mutex_lock" int main(int argc, char** argv) { pthread_cond_t* condition; pthread_mutex_t* mutex; char* message; int des_cond, des_msg, des_mutex; int mode = S_IRWXU | S_IRWXG; des_mutex = shm_open(MUTEX, O_CREAT | O_RDWR | O_TRUNC, mode); if (des_mutex < 0) { perror("failure on shm_open on des_mutex"); exit(1); } if (ftruncate(des_mutex, sizeof(pthread_mutex_t)) == -1) { perror("Error on ftruncate to sizeof pthread_cond_t\n"); exit(-1); } mutex = (pthread_mutex_t*) mmap(NULL, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, des_mutex, 0); if (mutex == MAP_FAILED ) { perror("Error on mmap on mutex\n"); exit(1); } des_cond = shm_open(OKTOWRITE, O_CREAT | O_RDWR | O_TRUNC, mode); if (des_cond < 0) { perror("failure on shm_open on des_cond"); exit(1); } if (ftruncate(des_cond, sizeof(pthread_cond_t)) == -1) { perror("Error on ftruncate to sizeof pthread_cond_t\n"); exit(-1); } condition = (pthread_cond_t*) mmap(NULL, sizeof(pthread_cond_t), PROT_READ | PROT_WRITE, MAP_SHARED, des_cond, 0); if (condition == MAP_FAILED ) { perror("Error on mmap on condition\n"); exit(1); } /* HERE WE GO */ /**************************************/ /* set mutex shared between processes */ pthread_mutexattr_t mutexAttr; pthread_mutexattr_setpshared(&mutexAttr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(mutex, &mutexAttr); /* set condition shared between processes */ pthread_condattr_t condAttr; pthread_condattr_setpshared(&condAttr, PTHREAD_PROCESS_SHARED); pthread_cond_init(condition, &condAttr); /*************************************/ if (!fork()) { sleep(10); pthread_mutex_lock(mutex); pthread_cond_signal(condition); printf("son signaled\n"); pthread_mutex_unlock(mutex); exit(0); } else { printf("father waits on condition\n"); pthread_mutex_lock(mutex); pthread_cond_wait(condition, mutex); pthread_mutex_unlock(mutex); printf("Signaled by son process, wake up!!!!!!!!\n"); pthread_condattr_destroy(&condAttr); pthread_mutexattr_destroy(&mutexAttr); pthread_mutex_destroy(mutex); pthread_cond_destroy(condition); shm_unlink(OKTOWRITE); shm_unlink(MESSAGE); shm_unlink(MUTEX); } return 0; } 要在进程之间共享,需要通过正确初始化的属性相应地初始化互斥量:http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutexattr_setpshared.html #include <pthread.h> ... pthread_mutex_t * pmutex = NULL; pthread_mutexattr_t attrmutex; /* Initialise attribute to mutex. */ pthread_mutexattr_init(&attrmutex); pthread_mutexattr_setpshared(&attrmutex, PTHREAD_PROCESS_SHARED); /* Allocate memory to pmutex here. */ /* Initialise mutex. */ pthread_mutex_init(pmutex, &attrmutex); /* Use the mutex. */ /* Clean up. */ pthread_mutex_destroy(pmutex); pthread_mutexattr_destroy(&attrmutex); (为了本示例的可读性,省略了错误检查) 这同样适用于应该在进程之间共享的条件变量:http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_condattr_setpshared.html #include <pthread.h> ... pthread_cond_t * pcond = NULL; pthread_condattr_t attrcond; /* Initialise attribute to condition. */ pthread_condattr_init(&attrcond); pthread_condattr_setpshared(&attrcond, PTHREAD_PROCESS_SHARED); /* Allocate memory to pcond here. */ /* Initialise condition. */ pthread_cond_init(pcond, &attrcond); /* Use the condition. */ /* Clean up. */ pthread_cond_destroy(pcond); pthread_condattr_destroy(&attrcond); (为了本示例的可读性,省略了错误检查) 另请参阅此答案:https://stackoverflow.com/a/2390670/694576 等待一个条件之前应该有一个 while 语句,像这样: pthread_mutex_lock(mutex); while(!conditionSatisfied) pthread_cond_wait(condition, mutex); pthread_mutex_unlock(mutex); while 信号应该通过以下方式完成: pthread_mutex_lock(mutex); conditionSatisfied = true; pthread_cond_signal(condition); pthread_mutex_unlock(mutex); 是的,必须在pthread_cond_wait之前锁定互斥量,但不必为pthread_cond_signal锁定。如果你回头看看你的代码,你会发现互斥量将被解锁两次,这是错误的标志......孩子也有可能在已被父母破坏的互斥量上调用解锁...... 顺便说一下,睡眠并不能保证父进程会先执行。为了确保这一点,您将需要……一个条件变量……


在另一个带有 EXPORT_SYMBOL 的 linux 模块上使用函数

我正在尝试执行我制作的 linux 模块的功能。但我没有成功。 这是项目 我创建了一个小函数来将 int 转换为 str float: #包括 我正在尝试执行我制作的 linux 模块的功能。但我没有成功。 这是项目 我创建了一个小函数来将 int 转换为 str float: #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include "service.h" #include "fp_printk.h" #define OURMODNAME "fp_printk" MODULE_AUTHOR("Guilherme Giacomo Simoes <[email protected]>"); MODULE_DESCRIPTION("This lib will show float-point in printk()"); MODULE_LICENSE("MIT"); MODULE_VERSION("0.4.1"); void fp_printk(int number, int decimal_places, char* destination) { static char buffer[32] = { 0 }; int buf_index = 30; int count_decimal_place = 0; int point_include = 0; for (; number && buf_index; --buf_index, number /= 10) { count_decimal_place++; if (!point_include && count_decimal_place > decimal_places) { buffer[buf_index] = '.'; buf_index--; point_include = 1; } buffer[buf_index] = "0123456789"[number % 10]; } strcpy(destination, &buffer[buf_index + 1]); } static int __init fp_printk_init(void) { printk(KERN_INFO "%s: initial execute module", OURMODNAME); return 0; } static void __exit fp_printk_exit(void) { printk(KERN_INFO "%s: module end", OURMODNAME); } module_init(fp_printk_init); module_exit(fp_printk_exit); EXPORT_SYMBOL(fp_printk); 转换后,将str复制到目标参数。 在我的测试模块中,我调用: #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <asm/fpu/api.h> #include <linux/slab.h> #include "../fp_printk.h" MODULE_AUTHOR("Guilherme Giacomo Simoes <[email protected]>"); MODULE_DESCRIPTION("LKP book:ch5/fp_in_lkm: no performing FP \ (floating point) arithmetic in kernel mode"); MODULE_LICENSE("Dual MIT/GPL"); MODULE_VERSION("0.1"); static int __init fp_in_lkm_init(void) { const int number = 1234; const int decimal_places = 2; char *r = (char*) kmalloc(sizeof("12.34"), GFP_KERNEL); printk(KERN_INFO "antes de executar\n"); extern void fp_printk(number, decimal_places, r); printk(KERN_INFO "teste apos a conversao"); printk(KERN_INFO "%s",r); printk(KERN_INFO "teste apos o printk"); return 0; } static void __exit fp_in_lkm_exit(void) { printk(KERN_INFO "removed\n"); } module_init(fp_in_lkm_init); module_exit(fp_in_lkm_exit); 但是当我运行 sudo dmesg 查看 printks 时,我只查看: [1210228.128703] test_fp_printk: antes de executar [1210228.128712] test_fp_printk: teste apos a conversao 它不打印 str 如果我在 module_init 中调用 fp_printk(),它会起作用。 static int __init fp_printk_init(void) { printk(KERN_INFO "%s: initial execute module", OURMODNAME); char *dest = kmalloc(sizeof("12.34"), GFP_KERNEL); fp_printk(1243, 2, dest); printk(KERN_INFO, "%s", dest); return 0; } 在您的fp_in_lkm_init()函数中,您正在尝试调用fp_printk()。像这样: extern void fp_printk(number, decimal_places, r); 但是,这不是调用函数的正确方法。在这里,您只是(不必要地)为函数添加一个函数原型,而不是调用它。 你只需要: fp_printk(number, decimal_places, r);


在链表中按名称字母顺序插入

#define _CRT_SECURE_NO_WARNINGS #define 暂停系统(“暂停”) #define CLS 系统 ("cls") #define FLUSH myFlush(); #include #include #include #define _CRT_SECURE_NO_WARNINGS #define PAUSE system("pause") #define CLS system ("cls") #define FLUSH myFlush(); #include<stdio.h> #include<stdlib.h> #include<string.h> #include <ctype.h> #include<time.h> //Function Prototypes void displayMenu(); int getChoice(int* option); void myFlush(); typedef struct personType { char name[100]; int age; float weight; struct personType* next; //pointer next points }Person; //to the next node typedef Person* LIST; //pointer to struct STUDENT named LIST main() { LIST temp = NULL, start = NULL, linkedList = NULL; //declare to variable of type LIST int ageTemp = 0, count = 1, counter; char nameTemp[100], response; float weightTemp; int option; do { getChoice(&option); switch (option) //begin switch { case 1: do { CLS; printf("\nEnter a name for person %d : ", count); scanf("%[^\t\n]", &nameTemp); FLUSH; printf("\nEnter the age for %s: ", nameTemp); scanf("%i", &ageTemp); FLUSH; printf("\nEnter the weight for %s: ", nameTemp); scanf("%f", &weightTemp); FLUSH; if (count == 1) { // create a node and store the information // create the head of the list linkedList = (LIST)malloc(sizeof(Person)); start = linkedList; // store the top/head/start of the list strcpy(start->name, nameTemp); start->age = ageTemp; start->weight = weightTemp; start->next = NULL; } else { temp = (LIST)malloc(sizeof(Person)); // create address of next node linkedList->next = temp; // assign next pointer in STUDENT struct the address of next node linkedList = temp; strcpy(temp->name, nameTemp); temp->age = ageTemp; temp->weight = weightTemp; temp->next = NULL; } printf("\nWould you like to enter another person?"); printf("\nEnter Y/N: "); scanf("%c", &response); FLUSH; count++; } while (response == 'Y' || response == 'y'); CLS; break; case 2: temp = start; // assigns temp to start // begin at the head of the list CLS; counter = 1; while (temp != NULL) //begin while { printf("Student %i: %s\t Age: %2i Weight: %.2f \n", counter, temp->name, temp->age, temp->weight); counter += 1; temp = temp->next; //iterates through the temp values } //end while printf("\n\n"); PAUSE; CLS; break; case 3: printf("Exiting program...\n"); printf("See you next time :)"); break; default: CLS; printf("That was not a valid selection..."); PAUSE; } // end Switch } while (option != 3); // Free The Memory while (start != NULL) //checks if start is pointing to null { temp = start; // points temp node to where start is pointing start = start->next; // iterates to next node that start points to free(temp); // frees memory allocated for list } // endwhile }// End of Main void myFlush() { while (getchar() != '\n'); } void displayMenu() { CLS; printf("Please select from the following options:\n\n"); printf("1. Add a Record.\n"); printf("2. Display All Records.\n"); printf("3. Quit.\n\n\n"); printf("Please enter a selection: "); } // end of displayMenu int getChoice(int* option) { displayMenu(); scanf("%i", &*option); FLUSH; return toupper(*option); } // ends getChoice function 我不知道如何按字母顺序对链表进行排序。链接列表本身工作正常,但我需要能够插入一个人的记录,因为结构和列表在代码中显示,而且还按字母顺序对它们进行排序,因此当我显示列表时,它将按该顺序显示。如果一个人的名字按字母顺序排在列表的原始头部之前,我将需要能够设置链接列表的头部。我看过其他链表帖子,但它们对深入解决我的问题没有帮助。


在这个收入管理中我的编辑记录功能不起作用

当我尝试编辑记录时此程序将新记录写入文件而不是编辑现有记录。 除了编辑现有记录外,此代码工作正常。 #包括 #包括 当我尝试编辑记录时此程序将新记录写入文件而不是编辑现有记录。 除了编辑现有记录外,此代码工作正常。 #include <stdio.h> #include <stdlib.h> #include <string.h> struct taxpayer { char name[50]; int Pancard_Number; int Mobileno; float income; float tax; }; void add_record(FILE *file) { struct taxpayer record; printf("Enter name: "); scanf("%s", record.name); printf("Enter 5-digit Pancard_number: "); scanf("%d", &record.Pancard_Number); printf("Enter Mobileno: "); scanf("%d", &record.Mobileno); printf("Enter income: "); scanf("%f", &record.income); if (record.income <= 25000) { record.tax = 0; } else if (record.income > 25000 && record.income <= 50000) { record.tax = (record.income - 25000) * 0.05; } else if (record.income > 50000 && record.income <= 75000) { record.tax = 1250 + ((record.income - 50000) * 0.2); } else if (record.income > 75000 && record.income <= 100000) { record.tax = 5520 + ((record.income - 75000) * 0.3); } else { record.tax = 11250 + ((record.income - 100000) * 0.4); } // record.tax = record.income * 0.1; // 10% tax rate fwrite(&record, sizeof(struct taxpayer), 1, file); printf("Record added successfully.\n"); } void show_allrecord(FILE *file) { // rewind(file); struct taxpayer record; fseek(file, 0, SEEK_SET); printf("%-20s %-20s %-20s %-20s \n", "Name", "PancardNo.", "Income", "TaxPaid"); while (fread(&record, sizeof(struct taxpayer), 1, file)) { printf("%-20s %-19d Rs.%-19.2f Rs.%-17.2f \n", record.name, record.Pancard_Number, record.income, record.tax); } } void search_record(FILE *file) { // char name[50]; int search; struct taxpayer record; printf("Enter pancard number to search: "); scanf("%d", &search); fseek(file, 0, SEEK_SET); while (fread(&record, sizeof(struct taxpayer), 1, file)) { if (record.Pancard_Number == search) { printf("%-20s %-20s %-20s %-20s \n", "Name", "PancardNo.", "Income", "TaxPaid"); printf("%-20s %-19d Rs.%-19.2f Rs.%-17.2f \n", record.name, record.Pancard_Number, record.income, record.tax); return; } } printf("Record not found.\n"); } // void edit_record(FILE *file) // { // char name[50]; // struct taxpayer record; // printf("Enter name to edit: "); // scanf("%s", name); // fseek(file, 0, SEEK_SET); // while (fread(&record, sizeof(struct taxpayer), 1, file)) // { // if (strcmp(record.name, name) == 0) // { // printf("Enter new income: "); // scanf("%f", &record.income); // if (record.income <= 25000) // { // record.tax = 0; // } // else if (record.income > 25000 && record.income <= 50000) // { // record.tax = (record.income - 25000) * 0.05; // } // else if (record.income > 50000 && record.income <= 75000) // { // record.tax = 1250 + ((record.income - 50000) * 0.2); // } // else if (record.income > 75000 && record.income <= 100000) // { // record.tax = 5520 + ((record.income - 75000) * 0.3); // } // else // { // record.tax = 11250 + ((record.income - 100000) * 0.4); // } // // record.tax = record.income * 0.1; // fseek(file, -sizeof(struct taxpayer), SEEK_CUR); // fwrite(&record, sizeof(struct taxpayer), 1, file); // printf("Record updated successfully.\n"); // return; // } // } // printf("Record not found.\n"); // } FILE *delete_record(FILE *file) { char name[30]; printf("Enter the name of the taxpayer to delete: "); scanf("%s", name); fseek(file, 0, SEEK_SET); struct taxpayer record; int found = 0; // Create a temporary file FILE *temp = fopen("temp.txt", "wb"); // Read each record from the file and write to the temporary file except for the one to be deleted while (fread(&record, sizeof(record), 1, file) == 1) { if (strcmp(record.name, name) == 0) { found = 1; } else { fwrite(&record, sizeof(record), 1, temp); } } fclose(file); fclose(temp); if (found) { // Delete the original file and rename the temporary file to the original file name remove("taxpayers.txt"); rename("temp.txt", "taxpayers.txt"); printf("Taxpayer with name %s has been deleted.\n", name); } else { printf("Taxpayer with name %s not found.\n", name); remove("temp.txt"); } // Open the original file for appending file = fopen("taxpayers.txt", "ab+"); if (file == NULL) { printf("Error opening file.\n"); exit(1); } return file; } int main() { FILE *file = fopen("taxpayers.txt", "ab+"); if (file == NULL) { printf("Error opening file.\n"); exit(1); } int choice; do { printf("\n1. Add New Record\n"); printf("2. List All Tax Payer along with Income Tax to be paid\n"); printf("3. Search\n"); printf("4. Edit\n"); printf("5. Delete Record\n"); printf("6. Exit\n"); printf("Enter your choice: "); fflush(stdin); scanf("%d", &choice); switch (choice) { case 1: add_record(file); break; case 2: show_allrecord(file); break; case 3: search_record(file); break; case 4: edit_record(file); break; case 5: delete_record(file); break; case 6: printf("Exiting...\n"); break; default: printf("Invalid choice. Please try again.\n"); break; } } while (choice != 6); fclose(file); return 0; } 我想要的是它从文件更新现有记录。 它还要求用户输入您要更新收入的姓名。 我希望它根据 pancard 号码和更新记录请求 pancard 号码和匹配记录。


我的代码没有一直运行到最后,我能做些什么来改变它?

所以我的代码应该读取一个文件并打印出读取的内容,同时将它组织成一个数据结构,但是代码只是在函数完成后停止运行。 #包括 所以我的代码应该读取一个文件并打印出读取的内容,同时将其组织成一个数据结构,但是代码在函数完成后就停止运行了。 #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct{ int StudentID; float ProvaIngresso; float NotaSecundario; float NotaCandidatura; int Escolha1, Escolha2, Escolha3, Escolha4, Escolha5; char curso1[4], curso2[4], curso3[4], curso4[4], curso5[4]; }Candidato; void ColocaCandidatos(Candidato *candidatos); int main() { Candidato candidatos[60000]; ColocaCandidatos(&candidatos[60000]); int x = 1; int y = 2; int z = x +y; printf("%d",z); return 0; } void ColocaCandidatos(Candidato *candidatos){ FILE *fp; char line[100]; char *token; int line_count = 0; int i= 0; //token pa controlar numero do candidato; // Open the CSV file for reading fp = fopen("Candidatos_N10_C20_O05.csv", "r"); if (fp == NULL) { printf("Error: could not open file\n"); exit(1); } // Read each line of the file and extract the string while (fgets(line, 100, fp) != NULL) { if (line_count > 0) { // Skip the first line token = strtok(line, ","); candidatos[i].StudentID = atoi(token); printf("\n%d",candidatos[i].StudentID); token = strtok(NULL, ","); candidatos[i].ProvaIngresso = atof(token); printf("\n%f",candidatos[i].ProvaIngresso); token = strtok(NULL, ","); candidatos[i].NotaSecundario = atof(token); printf("\n%f",candidatos[i].NotaSecundario); token = strtok(NULL, ","); candidatos[i].NotaCandidatura = atof(token); printf("\n%f",candidatos[i].NotaCandidatura); token = strtok(NULL, ","); candidatos[i].Escolha1 = atoi(token); printf("\n%d",candidatos[i].Escolha1); token = strtok(NULL, ","); strcpy(candidatos[i].curso1,token); printf("\n%s",candidatos[i].curso1); token = strtok(NULL, ","); candidatos[i].Escolha2 = atoi(token); printf("\n%d",candidatos[i].Escolha2); token = strtok(NULL, ","); strcpy(candidatos[i].curso2,token); printf("\n%s",candidatos[i].curso2); token = strtok(NULL, ","); candidatos[i].Escolha3 = atoi(token); printf("\n%d",candidatos[i].Escolha3); token = strtok(NULL, ","); strcpy(candidatos[i].curso3,token); printf("\n%s",candidatos[i].curso3); token = strtok(NULL, ","); candidatos[i].Escolha4 = atoi(token); printf("\n%d",candidatos[i].Escolha4); token = strtok(NULL, ","); strcpy(candidatos[i].curso4,token); printf("\n%s",candidatos[i].curso4); token = strtok(NULL, ","); candidatos[i].Escolha5 = atoi(token); printf("\n%d",candidatos[i].Escolha5); token = strtok(NULL, ","); strcpy(candidatos[i].curso5,token); printf("\n%s",candidatos[i].curso5); i++; } line_count++; } } 我什至尝试使用测试变量(x,y,z)来尝试找出问题所在,但我无法弄清楚,该程序根本不在函数之后运行男女同校的行,我不明白为什么。 我知道自问这个问题以来我迟到了两天,一些人已经评论了解决方案。如果有人需要,这里只是一个答案和摘要。 所以我复制了你的代码来用调试器检查。我创建了一个具有相同列标题的虚拟文件来进行测试。 问题 这是由 Weather Vane 确定的。您正试图指向数组中不存在的索引。我注意到在将令牌变量分配给列值的行中。您将名为 *restrict __s 的参数设置为 null。 token = strtok(NULL, ","); 解决方案 当它应该指向行变量时,像这样。 token = strtok(line, ","); 简而言之,代码是从 Null 值中读取 a ,并且您试图在转换这些 null 值时将它们分配给数组。因此,对于 Null 值,转换会失败,而 Null 值最终会分配给数组。 这解决了问题。我得到它来打印虚拟文件中的值并打印出最终消息。 这里是代码应该如何寻找你想做的事情。 守则 //The Header library files that the developer was using. #include <stdio.h> #include <stdlib.h> #include <string.h> //* So this is a structure that the developer needs to use for his application. typedef struct { int StudentID; // The Student's ID. float ProvaIngresso; // TryIncome? Sorry I am using google translate. float NotaSecundario; // Secondary Note. float NotaCandidatura; // NoteCandidacy. int Escolha1, Escolha2, Escolha3, Escolha4, Escolha5; // Pick1, Pick2, Pick3, Pick4, Pick5. char curso1[4], curso2[4], curso3[4], curso4[4], curso5[4]; // Cursor1, Cursor2, Cursor3, Cursor4, Cursor5. } Candidato; //* Here he declares a function with no body. void ColocaCandidatos(Candidato candidatos[]); //* The main entry point of the application. int main() { Candidato candidatos[100]; // Here the struct object gets declared. 60000 seems a bit excessive? ColocaCandidatos(candidatos); // Here the method is called. int x = 1; int y = 2; int z = x + y; printf("%d", z); // I think this is a basic way of checking if the code ran to the end. return 0; // The application ends here. } //* This is the method that reads the file. void ColocaCandidatos(Candidato candidatos[]) { // This is where the file handling is done. FILE *fp; // The FILE variable is declared. char line[100]; // An array with 101 available entries. char *token; // A token. The asterisk indicates it will be for a memory cursor variable. int line_count = 0; // How the user keeps track of what line he is on. int i = 0; // token pa controlar numero do candidato; // Translation: token to control candidate number // Open the CSV file for reading. fp = fopen("Candidatos_N10_C20_O05.csv", "r"); //If the FP variable is null, Then print an error saying the file could not be opened. if (fp == NULL) { printf("Error: could not open file\n"); // This prints the message. exit(1); // This exits with code 1, Meaning it will report it as an run with error's in the system logs. } // Read the lines of the file and extract the string as long as there is data in the file. while (fgets(line, 100, fp) != NULL) { if (line_count > 0) // Skip the first line { token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. candidatos[i].StudentID = atoi(token); // This converts a string to an Integer and assigns it to Student ID variable of the Candidato structure. printf("\n%d", candidatos[i].StudentID); // This prints the Student's ID, Take note that its getting the value from the structure object. So it's a way of checking the output. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. candidatos[i].ProvaIngresso = atof(token); // This converts a string to a float number and assign's it to the TryIncome variable. printf("\n%f", candidatos[i].ProvaIngresso); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. candidatos[i].NotaSecundario = atof(token); // This converts a string to a float number and assign's it to the SecondaryNote variable. printf("\n%f", candidatos[i].NotaSecundario); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. candidatos[i].NotaCandidatura = atof(token); // This converts a string to a float number and assign's it to the NoteCandidacy variable. printf("\n%f", candidatos[i].NotaCandidatura); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. candidatos[i].Escolha1 = atoi(token); // This converts a string to a int number and assign's it to the Pick1 variable. printf("\n%d", candidatos[i].Escolha1); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. strcpy(candidatos[i].curso1, token); // This copies the value and assign's it to the cursor1 variable. printf("\n%s", candidatos[i].curso1); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. candidatos[i].Escolha2 = atoi(token); // This converts a string to a int number and assign's it to the Pick2 variable. printf("\n%d", candidatos[i].Escolha2); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. strcpy(candidatos[i].curso2, token); // This converts a string to a float number and assign's it to the cursor2 variable. printf("\n%s", candidatos[i].curso2); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. candidatos[i].Escolha3 = atoi(token); // This converts a string to a float number and assign's it to the Pick3 variable. printf("\n%d", candidatos[i].Escolha3); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. strcpy(candidatos[i].curso3, token); // This converts a string to a float number and assign's it to the cursor3 variable. printf("\n%s", candidatos[i].curso3); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. candidatos[i].Escolha4 = atoi(token); // This converts a string to a float number and assign's it to the pick4 variable. printf("\n%d", candidatos[i].Escolha4); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. strcpy(candidatos[i].curso4, token); // This converts a string to a float number and assign's it to the cursor4 variable. printf("\n%s", candidatos[i].curso4); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. candidatos[i].Escolha5 = atoi(token); // This converts a string to a float number and assign's it to the Pick5 variable. printf("\n%d", candidatos[i].Escolha5); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. token = strtok(line, ","); // This apparently divides strings into tokens seperated by character's. strcpy(candidatos[i].curso5, token); // This converts a string to a float number and assign's it to the cursor5 variable. printf("\n%s", candidatos[i].curso5); // This print's the variable's value from the object. It's a way of checking if a value assigned to the struct. i++; // Increment the loop integer. } line_count++; // Increment the line count. } fp = fclose(fp); // Close the reader, It's good practice ;). } 我对代码和注释所做的其他更改 1.我更改了ColocaCandidatos的参数以使用普通对象数组。 2.我在函数结束时关闭阅读器,通常文件会在函数结束时关闭,但这是一个很好的做法。 3.用 60000 的数组大小声明候选对象似乎有点过分,每次运行时都会为数组分配至少 3.3Mb 的内存。 4.如果我有更多时间,我会尝试实现一种更好的方法来为 Candidato 对象分配值,而不是多次调用同一 3 行,但公平地说,并非所有行都是相同的。在尝试将值分配给变量之前,我还会添加一些检查空类型值的东西。


© www.soinside.com 2019 - 2023. All rights reserved.