Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
fist post on Stack Overflow.
If you have to read from a file structured composed by a line with a name and then 15 lines of numbers, so the file look like:
NAME1
NUM1
NUM2
...
...
...
NUM15
also you don't know how many lines has the file (but they obviously will be a multiple of 16), what is the simplest way to read every line and put it in a structure like:
struct something {
char name[128];
int nums[15]:
}
?
I used a while(fgets) to read every line until EOF and sscanf to analyze every line and put it in the structure, but i had some difficulties like doubled or causual numbers.
Edit: i can't post the code because i wrote it on University PC, so i can't access here right now
try fscanf(pFile, "%s %d %d %d (15times %d for 15 integers, other datatypes require different %...)", name, num1, num2, ....);
at some point fscanf will fail, you should be able to retrieve a EOF then (either using a different fscanf, fgets or whatever)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've created a struct with 2 char[] and one int. I created an array of this struct and scanfed several inputs to store data into the array. Then I used fprintf to write this data to the file. But when I open the file I get û before every new record. Idk why is it happening.
Here's the relevant code:
FILE *outputFile=fopen("1021.txt","ab");
int tickets=0,i=1;
struct air s[30];
printf("\nEnter Number of tickets:");
scanf("%d",&tickets);
for (i=1;i<=tickets;i++)
{
printf("\nEnter the name\t");
scanf("%s",&s[i].name);
printf("\nEnter the phone number\t");
scanf("%s",&s[i].phoneNo);
printf("\n Enter the address\t");
scanf("%s",&s[i].address);
printf("Your ticket is confirmed\t");
getch();
}
for (i=0;i<=tickets;i++)
{
printf("%s", s[i].name);
printf("%s", s[i].phoneNo);
printf("%s", s[i].address);
fprintf(outputFile,"%s",s[i].name);
fprintf(outputFile,"%s",s[i].phoneNo);
fprintf(outputFile,"%s",s[i].address);
}
Here's what I get in the file:
ûdalla03332228458dallaÈfsÇûÿÿÿÿàrancho03312041265dallabancho
Where are those unusual characters coming from?
Your input loop is
for (i=1;i<=tickets;i++)
but the output loop is
for (i=0;i<=tickets;i++)
So you are writing data to file from element [0] that you have no data entered for. That is why it is junk.
In C, arrays are indexed from [0], and neither of those loops is right. Please change both of them to
for (i = 0; i < tickets; i++)
There are other problems in the code too, but this addresses the immediate "uninitialised data" problem.
Edit: some other problems.
You opened the file in "binary" mode, but you are using it as a text file. I believe the distinction is only necessary in Windows.
FILE *outputFile=fopen("1021.txt", "at"); // change to "t"
The string address passed to scanf should not contain an & address-of (unlike an int). Just pass the array - it decays to the required pointer.
scanf("%s", s[i].name); // removed `&`
As you have not written any newline to file to demark your string data, when you read the data back in, you will not know where each ends and the next begins. So for example, add the newline like this
fprintf(outputFile, "%s\n", s[i].name); // added \n
You say one member is an int presumably the phone number, but you are inputting as a string. Yet it is a bad idea to store phone numbers as integers, because a) thay might contain a character such as '+' or b) may start with a leading 0 and that will be lost when you store as int. So change the struct member phoneNo to be a char array of adequate length.
The scanf format specifier %s will stop at the first whitespace it meets, so the input statements will be better as this, which will only stop when it finds a newline or hits the length limit:
int res = scanf("%29[^\n]", s[i].name);
where the array length defined was [30] (you did not show the struct). Alternatively you could research the use of fgets().
Finally, you should check the return value of the functions you are calling to see if they were successful. fopen will tell you if the file opened correctly. scanf will tell you the number of entries it scanned, and fgets tells you if it was successful too.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an array of integers, for example:
I memcpy the value into a char buffer, and the next time I retrieve it, it becomes a binary value, for example, 00000 -> 16. How do I avoid this?
Here is a snippet of my code:
char buf[BUFSIZE];
int outgoingPorts[4] = { 100000, 100001, 100002, 100003 };
memcpy(buf, &outgoingPorts[0], sizeof(outgoingPorts[0]);
printf("Port no: %i\n", buf);
Here, buf or the first outgoing port is 16 instead of 10000.
First of all, you're using wrong format specifier altogether, for the content of a char pointer to be printed, you need to use %s, provided that char array in null-terminated. Otherwise, you'll face undefined behaviour.
Then, if you really want to store an int value in a char array, the most suited way to go is to make use of snprintf() to print that value in the char array. Maybe the following pseudo-code will help you
char carr[16];
snprintf(carr, 16, "%d", outgoingPorts[0]);
printf("%s\n", carr); //should print 100000
FWIW, using wrong or mismatched format specifier invokes undefined behaviour.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Using fgetc() and/or read() how to i get the keys and the values from a file?
This is how it is written in the file:
<key1,val1><key2,val2><key3,val3>
And i need to put each key and value in a new array(to do linked-lists).
So, to insert in the file using '<' and '>' and ',' it's no problem. The problem is how to get them?
Any ideas?
Here's what I have.
FILE * file;
char* key;
char* value;
int c;//apparently I have to use an int
file=fopen("myfile.txt", "r");
c=fgetc(file);
while(c != EOF)
{
c=fgetc(file);
if(c == '<'){
for(int i=0; c != ','; i++)
{
key[i]=fgetc(file);
}
}
}
This is till the first comma. Now I lack a little of algorithm conception. Help please.
Does it have to be fgetc and read ? .. Here is one way to do this :
while(!feof(your_file_name)){
bzero(line, sizeof(line)); // line is a char array ... make sure its of sufficiently large size
fgets(line,100,your_file_name); // I am reading 100 characters .. you can change that number as per your file accordingly
}
fclose(your_file_name);
sscanf(line,"<%d,%d><%d,%d><%d,%d>",&key1,&val1,&key2,&val2,&key3,&val3); // assuming keys and vals are ints
What you are doing in your code is reading the file character by character .. Why go through all that pain?
using fgets will read the entire file in one go ... then knowing the format of the file sscanf is immensely powerful tool to recover info from that
Ok so you posted in comments that keys and vals are strings .. so change the sscanf to this:
sscanf(line,"<%[^,]%[^>]<%[^,]%[^>]<%[^,]%[^>]",key1,val1,key2,val2,key3,val3);
Ok so let me explain
When dealing with the strings in sscanf you have to specify the delimiting character.
So this <%[^,] tells sscanf - start reading a string from after this < character and read it until you reach , character ...
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i am currently struggling about couldn't output(printf) or correctly read the binary.
The following code resulted as (fread: Success) though.
if (fread(list, sizeof(struct Ticket), 10, fp) == 10){
perror("fread");
}
then i try to printf with the following code:
for ( i = 0; i < 10; i++ ) {
printf("%d\t%s\t%d\n", list[i].code, list[i].station, list[i].price);
}
Resulted messy unidentify code(although it was 10 line).
also, when i try to go forward with following code:
printf("\nPlease submit your destination\n");
scanf("%d\n", dec);
fprintf(stdout, "%d\t%s\t%d\n", list[dec-1].code, list[dec-1].station, list[dec-1].price);
Error appeared as Segmentation violation after input at scanf.
P.S. The fwrite was tested with perror("fwrite");
and resulted success.
Sorry for poor english and programming.
would really appreciate if anyone could help.
Thanks
If you want to print formatted output,use fscanf instead of fread.
fscanf() is used for reading from text files (i.e. readable by humans)
fread is used for reading from binary files (i.e. in formats used
by computers internally).
And you are getting segmentation violation since you have written scanf in wrong way.It should be
scanf("%d\n", &dec);
You are printing output on screen using format specifiers.Then you should read your data using format specifier.No doubt you can read any file using fread
You can read use of fread here
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am writing a program in which stdin is read into a buffer, then processed. The vast majority of these items that need to be processed are strings (or well, character arrays). However, I do have one item that needs to be read in as a character array and then converted to int for ease of use in the future.
for(i=0; i<n; i++){
num[i] = buff[(i)];
printf("%c", num[i]);
}
convert = atoi(num);
So I know for sure that the correct group of characters is being read into num because the printf for that is correct. However, when I try to print convert I end up getting 0, and I'm very perplexed as to what I'm doing wrong. I know that the 0 return means that a valid conversion could not be performed, but I don't know what's making it invalid. Any tips?
EDIT: Sorry for not including these before >_<
n is the number of chars in the buff array
buff is the buffer array stdin is read into
atoi is a function that gives you no means to analyze error conditions. On top of that, it produces undefined behavior in overflow situations. Don't ever use atoi (or atof or anything from ato... group) in real-life programs. It is practically useless.
To perform string-to-number conversions use strtol (and other functions from strto... group).
Now, what is inside your num at the moment you call your atoi? Is your num properly zero-terminated?