I need to write a simple program that reads numbers from a file, then stores those numbers in an array. The last number in the file is 0 so the program knows when to reading.
When I execute the program, Dec C++ crashes. I went online for solutions and changed the settings accordingly but that didn't work. I ran other programs I have and it works fine, which makes me think there's something wrong with the code.
Any ideas?
#include <stdio.h>
int main(){
int i, j=0, k;
int values[20];
FILE*ptr;
ptr = fopen("input.txt", "r");
fscanf(ptr, "%d", &i);
while (i=!0){
values[j]=i;
j++;
fscanf(ptr, "%d", &i);
}
for (k=0; k<20; k++)
printf("%d\n", values[k]);
fclose (ptr);
return 0;
}
Another typo:
while (i=!0){
should be:
while (i != 0){
Your code was assigning !0 to i, instead of comparing i with 0. !0 is 1, so you had an infinite loop, and you were writing beyond the bounds of the array.
Also note that if the file has more than 20 numbers in it, you'll write outside the array. And if it has fewer than 20 numbers, the loop that prints values[k] will read uninitialized array entries.
There are a couple of things that are wrong with the code:
You are not checking for error after opening input.txt
While i=!0 is syntactically correct it probably does not do what you want !0 is 1, so it is the same as i=1, you are putting value 1 into i
To help you with debugging:
add printf() statements to your code to verify that you reached a certain line and to check the values of the variables
learn to use a debugger
Related
I am trying to write numbers from 1, up to 400 in a text file. I am using the code below, which is running without any errors, but the file is being left empty.
Any help would be appreciated.
#include <stdio.h>
int main(void)
{
FILE *filePointer;
filePointer = fopen("file.txt","w");
int i;
for(i=0; i > 400; i++)
{
fputs("%d, ",i,filePointer);
}
fclose(filePointer);
return(0);
}
No, there's no way that compiled without some serious-sounding warnings at least.
You're using fputs() as if it were fprintf(), passing it an integer instead of a FILE pointer (which the compiler should not allow) and an extra argument (which the compiler should not allow).
Also your for loop is broken. The middle part is an expression that should be true for as long as the loop should run, not the other way around.
You meant:
for(i = 0; i < 400; ++i)
{
fprintf(filePointer, "%d, ", i);
}
Also, you should check that the file really did open before assuming it did. I/O can fail.
Apart from the fputs() usage, the problem is:
for(i=0; i > 400; i++)
If you initialize a variable with zero and perform a loop as long as it's greater than 400, that won't last too long.
The fputs syntax seem wrong. I think it is:
int fputs(const char *str, FILE *stream)
Pick #unwind's approach (as mentioned above) but if you still want to use fputs then your fputs line should be expanded into 3 lines:
char temp[4]; // String to store 3-digit number + '\0'
sprintf(temp, "%d, ", i); // Prepare a string for a given number
fputs(temp, filePointer); // Write the string to the file
This should work. #happycoding :)
PS: You seem to be following a bit C++ standard in declaring a variable anywhere. It is not pure C. #justsaying
Its my first question, so I hope you guys can help. In class, I was tasked with writing a C code that reads a group of strings from 1 file, and print them in another file, along with the ASCII codes of each character in the string, and the sum of the ASCII code values. The code below compiled, but did not execute. Is the code right, but I did something wrong, or is the code simply wrong. Thanks a bunch.
Note: the first file reads from a text file named list, and the code prints into a text document named list2.
#include <stdio.h>
int main(void)
{
FILE *file1, *file2;
file1 = fopen("list.txt", "r");
if (file1==NULL)
{
puts(" File not exisiting\n");
}
file2 = fopen("list2.txt", "w");
if (file2==NULL)
{
puts(" File could not open \n");
}
char a[5];
fscanf(file1, "%s", a);
int b,c;
while (a[5]!=EOF)
{
for (int i=0;i<5;i++)
{
fprintf(file2, "%c", a[i]);
b=a[i];
fprintf(file2, "%d", b);
c+=b;
}
}
fprintf(file2, "%d", c);
return 0;
}
Point 1. With a definition like
char a[5];
using
while (a[5]!=EOF)
invokes undefined behaviour.
You're facing off-by-one error. Remember, array index in c starts from 0. The valid access it at most upto a[4].
Point 2. fscanf(file1, "%s", a); is unsafe. It can cause buffer overflow. Atleast, you need to write
if ( fscanf(file1, "%4s", a) != 1)
{
//scanning not successful, take necessary measures
}
//otherwise, continue nomal execution.
Point 3. The logic for while loop is not correct. You don't have a break condition there.
Point 4. c+=b;, here c is used uninitalized. read-before-write scenario. Again, undefined behaviour. Remember, auto local variables doesnot get initialized to 0 or some value automatically. You've to initialize explicitly.
Point 5. Do not continue normal execution if if (file1==NULL) condition satisfies. Only printing a message is not sufficient. You should discontinue the program and avoid using file1, file1 etc.
Credits for point 5: user4402433
Include return in the file check as
if (file1==NULL)
{
puts(" File not exisiting\n");
return 0;
}
as there is no use of proceeding with the code if any one of the file is opened.
Also initialize the value of c=0; before while so that any garbage value can be avoided.
The array a[] has to be indexed to update the file content. So place the
fscanf(file1, "%s", a[i]);
inside the for() loop . This is to avoid buffer overflow which occurs in rare cases.
I am currently trying to learn the C programming language and am using Kernighan and Ritchie's The C Programming Language, Second Edition. I am trying to write a program similar to an example they give in the book in chapter one regarding text streams.
My program is supposed to print out a text file to the terminal and then count the number of characters before printing that figure too. This is my code:
#include <stdio.h>
int main()
{
int count = 0, c;
while ((c = getchar()) != EOF) {
count++;
putchar(c);
}
printf("\n%d characters\n", count);
return 0;
}
This is the output:
This is a simple file
With two very small lines
I mean three
1 characters
But when I add in this line below count++:
printf("%d", count);
The result is:
1T2h3i4s5 6i7s8 9a10 11s12i13m14p15l16e17 18f19i20l21e22
23W24i25t26h27 28t29w30o31 32v33e34r35y36 37s38m39a40l41l42 43l44i45n46e47s48
49I50 51m52e53a54n55 56t57h58r59e60e61
1 characters
This means that count is being incremented, but I cannot access its value from outside of the while loop. I thought that if the declaration of the variable (in this case int count = 0 is outside the loop), then the value could still be reached after the loop.
If it makes a difference, this is what I call it with:
./example <text.txt
Am I making a silly mistake? Any help would be appreciated. Thanks
Update
I do not know if it makes a difference, but the compiler I am using is: powerpc-apple-darwin9-gcc-4.0.1. Is that what the problem is?
Update 2
This is the command I used to compile the source: gcc -Wall example.c -o example. A weird thing has just happened though. It worked perfectly when I ran this:
#include <stdio.h>
int main()
{
int count = 0, c;
while ((c = getchar()) != EOF) {
count++;
putchar(c);
}
printf("x");
printf("\n%d characters\n", count);
return 0;
}
The output was:
This is a simple file
With two very small lines
I mean three
61 characters
The only difference between this code and the code above is the printf("x") line. I don't understand why it suddenly works if I print something else and I don't understand why it isn't visible. Any character can be put in the command and the same result happens. If more than one character is added, then the second one, and any after that, is printed.
Most likely your reference of characters to where characters are stored in memory is incorrectly coded which is why your output comes out like that. Ensure that the file and text within are correctly referenced. Other than that, the code seems OK.
I think this is what you should do:
int count = 0, c;
FILE *file = fopen("example.txt", "r");
while ((c = getc(file)) != EOF) {
count++;
putchar(c);
}
printf("\n%d characters\n", count);
fclose(file);
Try issuing a fflush(stdout) immediately before the
printf("\n%d characters\n", count);
FYI: your origninal code executes as expected on Ubuntu 14.04 Linux.
/edited/
I'm new here.
I have a text file that reads:
6
<cr>
R 0
R 1
R 4
R 36
R 0
R 4
This is what I have. I want to read each line into an array so that I can convert that array into an integer so I can print only the numbers of whichever line I want later.
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
FILE *fr; /*declares file pointer*/
int i, j, num[32];
char array[32][32], input_file[32], line[32];
printf("Enter file: ");
fflush(stdin);
scanf("%s", input_file);
fr = fopen(input_file, "r");
for(i=0;i<32;i++)
for(j=0;j<32;j++){
array[i][j] = \'0';
}
for(i=0;i<32;i++){
line[i] = '\0';
}
if(fr != NULL){
while(fgets(line, sizeof(line), fr) != NULL){
strcpy(array[i],line);
num[i] = atoi(array[i]);
i++;
printf("%d\n", num[i]);
}
}fclose(fr);
else{
perror(input_file);
}
}
I'm not getting any errors but it isn't printing the right thing; this is what it prints:
-370086
-370086
-370086
-370086
-370086
-370086
-370086
-370086
Can anyone explain to me what is going wrong?
I think I'd handle this a bit differently. Though you haven't stated it explicitly, I'm going to assume that the first number is telling us how many more lines of letters/numbers we're going to read (not including the blank line). So, we want to read that, then read the rest of the lines, ignoring any leading non-digits, paying attention only to the numbers.
If that's correct, we can simplify the code somewhat:
int num_lines;
int i;
int *numbers;
fscanf(infile, "%d", &num_lines); // read the number of lines.
numbers = malloc(sizeof(int) * num_lines); // allocate storage for that many numbers.
// read that many numbers.
for (i=0; i<num_lines; i++)
fscanf(infile, "%*[^0123456789]%d", numbers+i);
// the "%*[^0123456789]" ignores leading non-digits. The %d converts a number.
There are several issues:
You're never setting input_file to anything, so you seem to be opening a random file.
You're double-using i in the nested loops.
You're not showing array at all, so it's impossible to tell how it's declared.
You are increasing the loop index before using it to print the number, so you're always "missing" and printing the number in the next (not yet written) slot.
You should use memset() to clear the arrays if you're worried. There's no need to clear arrays that are going to be overwritten, such as line which is written to by fgets().
Assuming array is a char array, when you do:
...
strcpy(array[i],line);
num[i] = atoi(array[i]);
...
Your actually converting the entire line and not the integer in it. You should consider using fscanf, or at least search for the integer inside the line variable and convert it.
Doing atoi(array[i]) is the same as atoi("R 32\n") for example.
Im currently learning C through random maths questions and have hit a wall. Im trying to read in 1000 digits to an array. But without specifiying the size of an array first i cant do that.
My Answer was to count how many integers there are in the file then set that as the size of the array.
However my program returns 4200396 instead of 1000 like i hoped.
Not sure whats going on.
my code: EDIT
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
FILE* fp;
const char filename[] = "test.txt";
char ch;
int count = 0;
fp = fopen(filename, "r");
if( fp == NULL )
{
printf( "Cannot open file: %s\n", filename);
exit(8);
}
do
{
ch = fgetc (fp);
count++;
}while (ch != EOF);
fclose(fp);
printf("Text file contains: %d\n", count);
return EXIT_SUCCESS;
}
test.txt file:
731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511
125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749
303589072962904915604407723907138105158593079608667017242712188399879790879227492190169972088809377665727333001053367881220235421809751254540594752243
525849077116705560136048395864467063244157221553975369781797784617406495514929086256932197846862248283972241375657056057490261407972968652414535100474
821663704844031998900088952434506585412275886668811642717147992444292823086346567481391912316282458617866458359124566529476545682848912883142607690042
242190226710556263211111093705442175069416589604080719840385096245544436298123098787992724428490918884580156166097919133875499200524063689912560717606
0588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
Any help would be great.
You forgot to initialize count, so it contains random garbage.
int count = 0;
(But note that with this change it's still not going to work, since %d in a scanf format means read as many digits as you find rather than read a single digit.)
Turn on your compiler's warnings (-Wall), it will tell you that you didn't initialize count, which is a problem: it could contain absolutely anything when your program starts.
So initialize it:
int count = 0;
The other problem is that the scanfs won't do what you want, at all. %d will match a series of digits (a number), not an individual digit. If you do want to do your counting like that, use %c to read individual characters.
Another approach typically used (as long as you know the file isn't being updated) is to use fseek/ftell to seek to the end of the file, get the position (wich will tell you its size), then seek back to the start.
The fastest approach though would be to use stat or fstat to get the file size information from the filesystem.
If you want number of digits thin you tave to do it char-by-char e.g:
while (isdigit(fgetc(file_decriptor))
count++;
Look up fgetc, getc and scanf in manpages, you don't seem to understand whats going on in your code.
The way C initializes values is not specified. Most of the time it's garbage. Your count variable it's not initialized, so it mostly have a huge value like 1243435, try int count = 0.