| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
一个较为简单的读取一个txt文档中的每一行 
代码如下,但每次输入时总会显示“cannot open file" 而且我已经把commands.txt放进程序同一目录下,却还是如此,请大佬指正。 
#include <stdio.h> 
#include <string.h> 
 
int main () 
{ 
    FILE *fp; 
    int n = 0; 
    char expression[256]; 
 
    // open the file 
    if (!(fp = fopen("commands.txt","rt"))) 
    { 
        printf("cannot open file!\n"); 
        return -1; 
    } 
    // read the file line by line 
    do{ 
        if(fgets(expression, 256, fp)) 
        { 
            // remove the '\n' if it exists 
            if (expression[strlen(expression)-1] == '\n') 
                expression[strlen(expression)-1] = '\0'; 
            // do whatever you want for the line 
            printf("line %d: %s\n", ++n, expression); 
        } 
    } 
    while(!feof(fp)); 
    fclose(fp); 
    return 0; 
}
这样,你将 commands.txt 文件放到C盘根目录下,试一下我这个程序:
  
- #include <stdio.h>
 
 - #include <string.h>
 
  
- int main ()
 
 - {
 
 -     FILE *fp;
 
 -     int n = 0;
 
 -     char expression[256];
 
  
-     // open the file
 
 -     if((fp=fopen("c:\\commands.txt","rt"))==NULL)
 
 -     {
 
 -         printf("cannot open file!\n");
 
 -         return -1;
 
 -     }
 
 -     // read the file line by line
 
 -     do{
 
 -         if(fgets(expression, 256, fp))
 
 -         {
 
 -             // remove the '\n' if it exists
 
 -             if (expression[strlen(expression)-1] == '\n')
 
 -                 expression[strlen(expression)-1] = '\0';
 
 -             // do whatever you want for the line
 
 -             printf("line %d: %s\n", ++n, expression);
 
 -         }
 
 -     }
 
 -     while(!feof(fp));
 
 -     fclose(fp);
 
 -     return 0;
 
 - }
 
 
  复制代码 
 
 
 
 |   
 
 
 
 |