开发者

Problem with fopen()

开发者 https://www.devze.com 2023-03-08 20:18 出处:网络
So I am writing a little utility to format 开发者_如何学运维my inventory file is such a manner that I can import it to a preexisting db. I am having a large issue trying to just do fscanf. I have read

So I am writing a little utility to format 开发者_如何学运维my inventory file is such a manner that I can import it to a preexisting db. I am having a large issue trying to just do fscanf. I have read tons of file in c in the past. What am I doing wrong here.

Edit based on Christopher's suggestion still getting NULL.

#include <stdio.h>
#include <string.h>

int main ()
{

FILE* stream;
FILE* output;
char sellercode[200];
char asin[15];
string sku[15];
string fnsku[15];
int quality;

stream = fopen("c:\out\dataextract.txt", "r");
output = fopen("c:\out\output.txt", "w");

if (stream == NULL)
{
    return 0;
}

for(;;)
{
    //if (EOF) break;
    fscanf(stream, "%s", sku);
    fprintf(output, "%s %s  %s  %s  %i\n", sku, fnsku, asin, quality);
}
 return 0;
 }


if (stream = NULL)
{
    return 0;
}

should be

if (stream == NULL)
{
    return 0;
}


There's actually a lot of problems here. Christopher and mah (in the comment) mentions some of them. But a bigger problem is that you're not allocating any space to read (and write) your data.

By having string sellercode = ""; (p.s., do not define a "string" type, you're only hurting yourself here), you're pointing to a readonly array of char. You need to actually leave some memory here to read your data in to otherwise you're risking corrupting your memory.

These variables should be declared:

char sellercode[SOME_REASONABLE_SIZE];
char asin[SOME_REASONABLE_SIZE];
char sku[SOME_REASONABLE_SIZE];
char fnsku[SOME_REASONABLE_SIZE];

with some value of SOME_REASONABLE_SIZE.


You should also always close your files explicitly. Never leave them open.


Last thing I noticed now that you mention it is that you use backslashes in your paths but they are unescaped. You'll have to escape them.

stream = fopen("c:\\out\\dataextract.txt", "r");
output = fopen("c:\\out\\output.txt", "w");


Backslash is escape character inside strings. Use forward slash in your pathnames. "c:/foo/bar.txt"

0

精彩评论

暂无评论...
验证码 换一张
取 消