[英]I'm trying to read only the first 3 chars from a file - c
Hi I'm building an app which will check the numbers in the file are all fixed, and if not - to fix them (Depending on specific country codes). 嗨,我正在构建一个应用程序,该程序将检查文件中的数字是否全部固定,如果不是,则进行修正(取决于特定的国家/地区代码)。 In order to check if the number is good I first need to look at the country code, and for that I need to read the first 3 chars (From a phone number in file) to see if the number even have a country code.
为了检查该号码是否正确,我首先需要查看国家/地区代码,为此,我需要阅读前3个字符(从文件中的电话号码),以查看该数字是否还包含国家/地区代码。 When I'm running the code below I'm getting
当我运行下面的代码时,
Stack around the variable 'country_code' was corrupted".
变量“ country_code”周围的堆栈已损坏”。
I think my reading the specific 3 char from the string is making the problem, but I can't find what exactly is doing it. 我认为我从字符串中读取特定的3个字符会造成问题,但是我找不到确切的操作方法。
void fix_file_il_country(char *filename)
{
FILE *f = fopen("1.txt", "r"); //The file to check from
if (f == NULL)
{
printf("EROR\n");
return;
}
FILE *fp = fopen(filename, "w"); //The new file with fixed numbers
if (f == NULL)
{
printf("EROR\n");
return;
}
char num[20];
char country_code[3];
fscanf(f, "%3s %s", &country_code, &num);
while (!feof(f))
{
if (strlen(num) == 12)
if (country_code == "972")
fprintf(fp, "%s\n", num);
fscanf(f, "%3s %s", &country_code, &num);
}
fclose(f);
fclose(fp);
}
The numbers like: 9725XXXXXXXX should be written the new file Numbers like: 123XXXXXXXXX, or number with more\\less chars than 12 shouldn't been written. 像这样的数字:9725XXXXXXXX应该被写入新文件。像这样的数字:123XXXXXXXXX,或者不超过12个字符的字符数不应该被写入。
You haven't provided space for the null terminator. 您尚未为空终止符提供空间。
char country_code[3];
should be 应该
char country_code[4];
Also, see Why is “while ( !feof (file) )” always wrong? 另外,请参见为什么“ while(!feof(file))”总是错误的?
I can see two potential issues: 我可以看到两个潜在的问题:
the char
array needs to store also the null termination, so it should be defined as char
数组还需要存储空终止符,因此应将其定义为
char country_code[4]
otherwise it is not possible to define the end of the array. 否则无法定义数组的结尾。
In the scanf
you are passing the pointer of a pointer. 在
scanf
您正在传递指针的指针。 You should change 你应该改变
fscanf(f, "%3s %s", &country_code, &num)
to 至
fscanf(f, "%3s %s", country_code, num)
without the &
. 不带
&
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.