2015-05-30 39 views
-2

我似乎无法打开这个.txt文件,它也不适用于.csv文件 我如何打开它? (这是一个程序,我尝试做出一个短语搜索一个CSV文件中)文件不会打开使用fopen

#include <stdio.h> 
#include <stdlib.h> 

#define ARRAY_WIDTH 320 

int main(int argc, char *argv[]) { 

    int i = 0, j = 0; 
    char bigString[200]; 
    FILE* csv; 
    csv = fopen("C:\Users\Ofek\Desktop\Folder\source.txt","r+t"); 
    while (feof(csv) != 1) 
    { 
     if (fgetc(csv) != '\n') 
     { 
      char bigString[i] = fgetc(csv); 
      i++; 
     } 
    } 
} 
+1

您收到了什么错误?当您尝试打开文件时,是否还有更多详细信息可以说明发生了什么问题? –

回答

1

替换所有的单反斜线以两个反斜杠:

C:\\Users\\Ofek\\Desktop\\Folder\\source.txt 

否则反斜杠之后的字符会解释为控制字符。

+0

或者,使用'/',这在Windows上是完全有效的。 – cdarke

1

发布的代码有几个问题。这里有几个:

1) do not use 'feof()' for a loop control, it will not work as expected. 
2) when setting the bigString[i] variable, a second call to fgetc() is used. That results in the first, 3, 5, 7, etc characters being lost. 
Suggest: save the results of the call to fgetc() in the 'if' statement and use that saved value. 

以下代码纠正了发布代码中的'大部分'问题。

#include <stdio.h> 
#include <stdlib.h> 

int main(void) 
{ 

    int i = 0; 
    int inputChar; 
    char bigString[200] = {'\0'}; 

    FILE* csv; 
    if(NULL == (csv = fopen("C:\\Users\\Ofek\\Desktop\\Folder\\source.txt","r+t"))) 
    { // then fopen failed 
     perror("fopen for source.txt failed"); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, fopen successful 

    while (EOF != (inputChar = fgetc(csv))) 
    { 
     if ('\n' != inputChar) 
     { 
      bigString[i] = inputChar; 
      i++; 
     } 
    } 
    printf("Input file, without newlines: %s\n", bigString); 
    return(0); 
} // end function: main