I'm C newbie and i'm having a tough time with my first assignment :sad:

The assignment is on creating a Number Puzzle.....apparently it's the newest craze in Toronto and my prof is a big fan....unfortunately

I'm trying to read in a file which looks like this:
9,8, ,5,,4,,
7,3,1, ,5

this is what i want to do..
-Read in the file and use fscanf to store everything in an array of chars called tempGrid. (I don't want the extra white space between commas)
-then tempGrid to another 1D array pointed to by a pointer called *grid.....WITHOUT the commas.
-And just print out the result

Obviously this is not my whole assignment, only like 1% of it.
I've tried to do this simple thing for two days now and i can't seem to get it to work.
PLEASE HELP!!

Another question: does fscanf write the result straight to an array or do i have to pass in a pointer that points to an array?

Thanks for any help. I really appreciate it. I'm on the verge of tearing my hair out in frustration :sad:

Recommended Answers

All 16 Replies

Post the code you have so far -- remember to use code tags.

this is what i have so far:

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


int main(int argc, char *argv[])
{
	FILE *f_read;
	int num;
	char tempGrid[50];
	int i,t;

	char *grid;

	grid = (char *)malloc(sizeof(char) * 9 * 9);

	if (argv[1] != NULL){
		f_read = fopen(argv[1], "r");
            	while ((num = fscanf(f_read, "%c",tempGrid))!= EOF){
			for (i =0; i < 50; i++){							grid[i] = tempGrid[i];
			}
		}
	}

	for (t = 0; t <50; t++)
		printf("%c\n", grid[t]);
	}
	return(0);
}

when i run it the characters the array stores is some other weird characters. I think i need to do some kind of conversion after the while loop before i store the chars.

In C, it may be better not to cast the return value of malloc.

grid = (char *)malloc(sizeof(char) * 9 * 9);

Checking the return value is always recommended. As is here.

f_read = fopen(argv[1], "r");

Checking return values will save you countless hours of debugging, so it's a good habit to start. Unless you like to pull your hair out for hours.

This line was missing a {.

for ( t = 0; t <50; t++ )

Here is a place to fix up:

while ( (num = fscanf(f_read, "%c", tempGrid))!= EOF )

I might go with something more like this.

for ( i = 0; i < 50 && fscanf(f_read, "%c", &tempGrid[i]) == 1; i++ )

You are only reading into the first element of tempGrd. Later you pretend you have filled the whole thing up.

grid[i] = tempGrid[i];

Multiplying by sizeof(char) is the long way of multiplying by one, which is pointless.

If the number of characters in the file may be less than your 50, it might be wise only to print out as many as were read.

Take another swing and we'll move forward from there.

for ( i = 0; i < 50 && fscanf(f_read, "%c", &tempGrid[i]); i++ )

Could you explain that line a bit?
I don't really undestand how "i <50 && fscanf..." part works

And also the malloc line was given to us by the prof. He said that we have to use that exact line. He said it's his way of making sure we don't use a 2D array for the assignment :p

for ( i = 0; i < 50 && fscanf(f_read, "%c", &tempGrid[i]); i++ )

Could you explain that line a bit?
I don't really undestand how "i <50 && fscanf..." part works

It just has two conditions to continue the loop -- that you don't overflow the buffer and that you successfully read some data (in the edited and fixed version the return value of fscanf is compared to 1).

And also the malloc line was given to us by the prof. He said that we have to use that exact line. He said it's his way of making sure we don't use a 2D array for the assignment :p

[sarcasm=thin]Great -- another professor who needs a few more lessons.[/sarcasm]

You seem engaged in this, so I'll post my working copy.

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

int main(int argc, char *argv[])
{
   char *grid = malloc(9 * 9);
   if ( grid )
   {
      int t, i = 0;
      if ( argc > 1 )
      {
         FILE *f_read = fopen(argv[1], "r");
         if ( f_read )
         {
            char tempGrid[50];
            puts("Just before while");
            while ( i < 50 && fscanf(f_read, "%c", &tempGrid[i]) == 1 )
            {
               if ( tempGrid[i] != ',' && !isspace(tempGrid[i]) )
               {
                  grid[i] = tempGrid[i];
                  ++i;
               }
            }
         }
      }
      for ( t = 0; t < i; t++ )
      {
         printf("%c\n", grid[t]);
      }
      free(grid);
   }
   return 0;
}

/* my output
H:\test>test file.txt
Just before while
9
8
5
4
7
3
1
5
*/

thank you so much for your help! :D
Now i can actually start on the assignment

Sorry, i am newbie...i want to ask to dave, where the read file command in the code?

I don't know what is wrong with my code please help...i am new at c programming

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include "stdafx.h"
int main( int argc, char *argv[])
{
    FILE *f1 , *f2;
    char pattern[100];
    char text[100];
    f1 = fopen( "C:\\data\\file1.txt" , "r");
    f2 = fopen ( "C:\\data\\file2.txt" , "r");
    if(f1 != NULL)
    {
         fread( pattern, sizeof(char), 100,f1);
    }
    if(f2 != NULL)
    {
         fread( text, sizeof(char), 100,f1);
    }



int i, j, main, sub,found;
main = sizeof(text);
sub = sizeof(pattern);

    for(i=0; i< main-sub; i++)

    {   found =1;
        for (j=0; j<sub ;j++);
        {
            if (pattern[j]!=text[i+j])
            {
                found=0;
                break;
            }
            else found=1;
        } 
    }
if(found) 
{return i;
printf("the pattern is found at: %d",i);
}

    fclose(f1);
    fclose(f2);

return -1;


}

i don't know what is wrong with my code...help me!!
I am new at c programming

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include "stdafx.h"
int main( int argc, char *argv[])
{
    FILE *f1 , *f2;
    char pattern[100];
    char text[100];
    f1 = fopen( "C:\\data\\file1.txt" , "r");
    f2 = fopen ( "C:\\data\\file2.txt" , "r");
    if(f1 != NULL)
    {
         fread( pattern, sizeof(char), 100,f1);
    }
    if(f2 != NULL)
    {
         fread( text, sizeof(char), 100,f1);
    }



int i, j, main, sub,found;
main = sizeof(text);
sub = sizeof(pattern);

    for(i=0; i< main-sub; i++)

    {   found =1;
        for (j=0; j<sub ;j++);
        {
            if (pattern[j]!=text[i+j])
            {
                found=0;
                break;
            }
            else found=1;
        } 
    }
if(found) 
{return i;
printf("the pattern is found at: %d",i);
}

    fclose(f1);
    fclose(f2);

return -1;


}

noob26891 it would be better to start your own thread with your problem, than to revive a one year old thread.
Also, please use correct indentation.
As a side note, why do you use int main( int argc, char *argv[]) in your main program, but still you don't use the int argc, char *argv[]. Also, I see you have included headers which are not supported in C, like <iostream.h>, headers like that are also noticed to be depreciated, and are not in use these days.
Another thing: I see you have a variable int main. I would suggest to change the name of that variable, because your function is called main, and if you do create a variable with the same name, the compiler will be confused, and it will yield errors or warnings. But still, what is your question? You just posted 52 lines of code, and said that something is wrong with your code, but you didn't say anything else about what it's suppose to do.

commented: what it do yes!! )) +2

A quick example:

#include <stdlib.h>
int main(){
    int main=4;
    printf("%d", main);
    return (0);
}
//warning: 'main' is usually a function [-Wmain]

Thank you Lucaci. :)
thanks for your time...:)
I wanted to read a pattern and a text from two separate files, store them in a char array and then use brute-force method to find the pattern in the text.
the text was not being read and the text array stored garbage values as i had done a static memory allocation..
this is the improved code...but it doesn't return "the pattern is found" even if the text has the pattern..

#include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include "stdafx.h"
    int main(  int found,int mains, int sub)
    {
        FILE *f_text , *f_pattern;

        f_text = fopen( "C:\\data\\file1.txt" , "r");
        fseek(f_text, 0, SEEK_END);
        int text_file_size = ftell(f_text);
        fclose(f_text);

        f_text = fopen( "C:\\data\\file1.txt" , "r");
        char *text;
        text = new char[text_file_size+1];
        text[text_file_size]='\0';
        if(f_text != NULL)
            {
                fread( text, sizeof(char), text_file_size,f_text);
            }
        fclose(f_text);


        f_pattern = fopen ( "C:\\data\\file2.txt" , "r");
            fseek (f_pattern,0, SEEK_END);
            int pattern_file_size = ftell (f_pattern);
        fclose(f_pattern);

        f_pattern = fopen ( "C:\\data\\file2.txt" , "r");
            char *pattern;
                pattern = new char[pattern_file_size+1];
        pattern[pattern_file_size]='\0';


            if(f_pattern!= NULL)
            {
                fread(pattern, sizeof(char),pattern_file_size ,f_pattern);
            }
        fclose(f_pattern);


    int index=-1;
    int i, j,k;
     mains= text_file_size;
     sub= pattern_file_size;
    for( i=0; i<=mains-sub; i++)
    {
        index =k=i;
            for(j=0;j<sub;j++)
            {
                if(pattern[j]==text[k])
                    {k++;}
                else {break;}
            }


            if(j=sub)
            {printf ("the string is found");}
            else return -1;

    }

    delete text;
    delete pattern;

    }

there is something wrong with the brute force implementation as the text array and the pattern array are reading and storing the files properly.

Are you sure that you are coding in C

pattern = new char[pattern_file_size+1];
delete text;
delete pattern;

Because my compiler complains about that. Use the allocation with malloc/calloc etc. and freeing the memory by free(pointer).
new/delete are from C++ | malloc/free are from C.
Here this might help you.

#include <iostream>
#include <cstdlib>
#include <stdio.h>

int main(){
    int text_file=5;
    char *text;
    text=(char*)malloc(text_file+1); //C style.
    char *text1;
    text1=new char[text_file+1]; //C++
    if (sizeof(text)==sizeof(text1)) std::cout<<"Yes.\n";
    else std::cout<<"No.\n";
    delete [] text1; //C++ style.
    free(text); //C style
    return (0);
}
/*
 * My output: 
 * Yes.
 */

Note that this is written in C++ in order to get the new/delete/cout stuff.
Another observation:
Line 58: if(j=sub) you instead of = == because with the = you are assigning a value to j, the sub value. The == operator checks for the equality.
Again, numerous warnings related to your main function:
warning: third argument of 'main' should probably be 'char **' [-Wmain]....
and you must put the return(0) at the end of your int main() funtion.

Another thing: are you working with binary files? fread works explicitly with binary files. If you want to just work on text files here's a list that might help you:
for binary files: fopen, fclose, fread, fwrite, fseek
for text files: fopen, fclose, fgetc, fgets, fputc, fputs, fprintf, fscanf
Search on the net about each of them, and learn how to use them.

And, beside that, you have other buggs. Here's the code with some modiffications:

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

int line_num(char *filename){
    FILE *f;
    char c;
    int lines = 0;
    f = fopen(filename, "r");
    if(f == NULL) return (0);
    while((c = fgetc(f)) != EOF)
        if(c == '\n') lines++;
    fclose(f);
    if(c != '\n') lines++;
    return (lines);
}

int main(){
    FILE *f_text , *f_pattern;
    int found, text_ln=line_num("text.txt");
    f_text = fopen("text.txt", "r");
    fseek(f_text, 0, SEEK_END);
    int text_file_size = ftell(f_text);
    fclose(f_text);

    f_text = fopen("text.txt", "r");
    char *text;
    text = (char*)malloc (text_file_size+1);
    text[text_file_size]='\0';

    f_pattern = fopen ( "pattern.txt" , "r");
    fseek (f_pattern,0, SEEK_END);
    int pattern_file_size = ftell (f_pattern);
    fclose(f_pattern);

    f_pattern = fopen ( "pattern.txt" , "r");
    char *pattern;
    pattern = (char*)malloc (pattern_file_size+1);
    pattern[pattern_file_size]=0;
    if(f_pattern!= NULL){
        fgets(pattern, sizeof(char)+pattern_file_size, f_pattern);
    }
    int i, j, k;
    if(f_text != NULL && f_pattern!=NULL){
        for (;text_ln--;){
            fgets(text, sizeof(char)+text_file_size,f_text);
            for (i=0;i<text_file_size;i++){
                if (pattern[0]==text[i]){
                    k=i;
                    for (j=0;j<pattern_file_size;j++){
                        if (pattern[j]==text[k]){
                            k++;
                            if (j+1==pattern_file_size) found=1;
                        }
                        else break;
                    }
                }
            }
        }
    }
    fclose(f_text);
    fclose(f_pattern);

    if(found==1) printf ("The pattern was found.\n");
    else printf("The pattern wasn't found.\n");

    free (text);
    free (pattern);
    return (0);
}

Now, let's analize it a bit:

    int line_num(char *filename){
        FILE *f;
        char c;
        int lines = 0;
        f = fopen(filename, "r");
        if(f == NULL) return (0);
        while((c = fgetc(f)) != EOF)
            if(c == '\n') lines++;
        fclose(f);
        if(c != '\n') lines++;
        return (lines);
    }

will count the number of lines from a given file. Why would that be needed?, would you ask. Well, it's not mandatory, but I found it to be good further in the program. OK, so let me explain a bit why I need that.

fgets(text, sizeof(char)+text_file_size,f_text);

char * fgets ( char * str, int num, FILE * stream );
Get string from stream
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the End-of-File is reached, whichever comes first.

That's the definition I got out of the C++ site about the fget. So it says that it will read characters till, either EOF or the newline character appears. So, if your text has more than 1 lines, simply putting fgets will get the first line, and by chance, if the pattern is only in the second line, it will print out that the pattern wasn't found. So, I put that
line_num() function so that I know how many lines I have, and also, to parsh all the text, and not only one line. This is done in the

if(f_text != NULL && f_pattern!=NULL){
        for (;text_ln--;){
            fgets(text, sizeof(char)+text_file_size,f_text);

part.
Another thing, sice you're posing it in a C thread, I changed the memory allocation syntax from:

text = new char[text_file_size+1];

to

text = (char*)malloc (text_file_size+1);

and

delete text;

to

free (text);

Ok, moving on, I changed a bit the solving part, the algorithm I use is not the brightest, but it's a "brute-force method" so that should work just fine for you.
And, as a side note, please indent your code by the need of the syntax, not of the "importance" of the presented code:
So, if you have like

for (i=0;i<5;i++){
    if (a[i]==b[i]) printf("Same char at position %d in the array.\n", i);
    else printf("Different char at position %d in the array.\n", i);
}

do not indent like this

    for (i=0;i<5;i++){
    if (a[i]==b[i]) printf("Same char at position %d in the array.\n", i);
        else printf("Different char at position %d in the array.\n", i);
    }

it will not make any sence.
If you do have further questions, please, start your own thread regarding those questions.

int main(){
    int text_file=5;
    char *text;
    text=(char*)malloc(text_file+1); //C style.
    char *text1;
    text1=new char[text_file+1]; //C++
    if (sizeof(text)==sizeof(text1)) std::cout<<"Yes.\n";
    else std::cout<<"No.\n";
    delete [] text1; //C++ style.
    free(text); //C style
    return (0);
}

A small correction to my previous post: silly me:

#include <stdio.h>
#include <string.h>
int main(){
    char *p="hello";
    char *s="world";
    if (sizeof(p)==sizeof(s)) printf("Sizeof: Yes.\n");
    else printf("Sizeof: No.\n");
    if (strcmp(p,s)==0) printf("Strcmp: Yes.\n");
    else printf("Strcmp: No.\n");
    return (0);
}

sizeof(char*) always = sizeof(char*) but here, p!=s as contents.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.