用C读取数据

时间:2015-11-02 19:54:48

标签: c file scanf

因此,我的文件包含onPrepareOptionsMenu()格式的数据,例如

full_file_path #

我试图用

读取文件
C:/dev/Java/src/java/util/concurrent/ConcurrentHashMap.java 212
C:/dev/Java/src/java/util/HashMap.java 212
C:/dev/Java/src/java/lang/CharacterData02.java 190
C:/dev/Java/src/java/lang/CharacterData0E.java 190
C:/dev/Java/src/java/nio/DirectCharBufferS.java 123
C:/dev/Java/src/java/nio/DirectCharBufferU.java 123
...

然而输出像

那样是垃圾
int dup;
char file[MAX_LINE];
...
FILE *fp;
fp = fopen("OUTPUT100.txt", "r");
while (fscanf(fp, "%s %d\n", &file, &dup) == 1) {
   printf("%s %d\n", file, dup);
}
fclose(fp);

我做错了什么?

编辑:我的#34;仍在吐出垃圾"评论只是脑屁。我在while循环下面的循环中有一个printf,它正在吐出垃圾。向上滚动几百行后,我开始看到合理的数据。评论printf导致了预期的结果。工作阅读使用 has 0 duplciate lines of code RJ9 has 0 duplciate lines of code has 0 duplciate lines of code ▒▒" has 0 duplciate lines of code has 0 duplciate lines of code "A▒ has 0 duplciate lines of code has 0 duplciate lines of code 7▒cw has 0 duplciate lines of code has 0 duplciate lines of code has 0 duplciate lines of code 。谢谢大家。

3 个答案:

答案 0 :(得分:2)

像这样修改你的循环调用

while (fscanf(fp, "%s %d\n", file, &dup) == 2) {

正如@mjswartz所说,file是一个数组,当你将它传递给char*时会衰减到fscanf。另外fscanf将返回它设法检索的参数数量,并且每行扫描2个变量。

答案 1 :(得分:0)

好吧,fscanf返回成功格式说明符的数量,因此它会在成功时返回2,并且您要检查它是否返回1.您可能想要检查EOF字符而是从那里停止阅读。

此外,file变量是一个可用作指针的数组,因此您不应尝试引用它。

while (1)
{
    r = fscanf(fp, "%s %d\n", file, &dup);
    if( r == EOF ) 
       break;
    printf("%s %d\n", file, dup);
}

答案 2 :(得分:0)

关于这一行:

while (fscanf(fp, "%s %d\n", &file, &dup) == 1) {

fscanf()返回成功输入/转换的次数

即。如果成功,格式字符串有2个转换参数,那么它将返回2,而不是1.

请阅读/理解fscanf()

的手册页

格式字符串不应该有一个尾随的'\ n'(不像printf(),它几乎总是有一个尾随'\ n')

要使用任何“剩余”空白区域(如换行符),请在格式字符串中放置一个前导空格。

当前格式说明符'%s'没有最大长度修饰符,因此输入文件中的数据可能会溢出可用的输入缓冲区,从而导致可能导致seg错误事件的未定义行为。

注意:在C中,数组的名称会降级为指向数组第一个字节的指针,因此请不要获取数组的地址:file

建议:

while (fscanf(fp, " %#s %d\n", file, &dup) == 2) { 

其中#是值MAX_LINE-1。

发布的代码绝对不可能输出作为输出发布的文本。

建议发布实际代码,实际输出和预期输出。

注意:file是char数组的可怜名称。提出一些有意义的内容,例如buffer