fscanf fails reading tab values - c

I am writing a simple C program to read float values from a tab file using fscanf.
Here is the tab file:
> 7 <--------------this declares the number of pairs of values
> 4.0 5.0
> 5.5 4.0
> 1.0 5.0
> 5.0 2.5
> 2.0 2.0
> 4.0 2.0
> 1.0 1.5
Here is my program:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <string.h>
char filename[100];
FILE *fp;
int n=0;
int N;
double x[22];
double y[22];
int main(void) {
printf("Input filename: ");
fgets(filename, 100, stdin); //read filename
//check if enter sign exist in filename
N = (int)strlen(filename);
for (int i = 0; i < N; i++) {
if (filename[i] == '\n') {
filename[i] = '\0';
}
}
//printf("%s", filename);
fp = fopen(filename, "r"); //open file
if (fp == NULL) //check file
{
printf("\nCannot open input file %s\n", filename);
exit(1);
}
fscanf(fp, "%d", &n); //read Data
for (int i = 0; i < n; i++) {
fscanf(fp,"%f%f", &x[i], &y[i]);
}
fclose(fp); //close file
//check data retrieved
for (int i = 0;i < n;i++) {
printf("%f//%f//\n", x[i], y[i]);
}
The result is 14 values of 0.0000 rather than values in the tab file.

Related

Saving integers from a file into an array

I was hoping to get a bit of help, I am implementing an inversion counter algorithm to take in 50,000 intergers and display the inversions and time it took to run the algorithm, I am having a hard time allocating and saving the integers from the file into an array. My code complies and runs but nothing happens
here is what I have:
int main(int argc, char** argv)
{
int n, i;
int inversions=0;
int *A;
FILE *file;
char filename[100];
clock_t start, end;
double totalTime;
printf("Enter filename: ");
scanf("%s", filename);
file = fopen(filename, "r");
if(file == NULL)
{
printf("Error opening file!\n");
return 0;
}
fscanf(file, "%d", &n);
A = (int*) malloc(n * sizeof(int));
for(i = 0; i < n; i++) {
fscanf(file, "%d", &A[i]);
}
start = clock();
inversions = countInversionsBruteForce(A, n);
end = clock();
totalTime = (double) (end - start) / CLOCKS_PER_SEC;
printf("Brute Force Algorithm\n");
printf("Number of inversions: %d\n", inversions);
printf("Execution time: %f\n", totalTime);
I think I have noth allocated array size and saved it properly
Your program is incomplete so I was not able to compile it. Minimized the problem to just loading the data into your array:
Formatted code for readability.
Generated a suitable input file. Most likely this is your problem but you have not shared your input sample with us.
Added missing include files.
Remove argc, argv as you not using them.
Minimize scope of variables. Use size_t instead of int for unsigned values.
Max string size on obtaining file name
Check return value for scanf(), fopen(), fscanf().
Printing out the data read to demonstrate it's working.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
printf("Enter filename: ");
char filename[100];
if(scanf("%99s", filename) != 1) {
printf("scanf failed\n");
return 1;
}
FILE *file = fopen(filename, "r");
if(!file) {
printf("Error opening file!\n");
return 1;
}
size_t n;
fscanf(file, "%zu", &n);
if(!n) {
printf("n must be positive");
return 1;
}
int *A = malloc(n * sizeof(*A));
for(size_t i = 0; i < n; i++)
if(fscanf(file, "%d", &A[i]) != 1) {
printf("fscanf() failed\n");
return 1;
}
printf("n = %zu\n", n);
printf("A = ");
for(size_t i = 0; i < n; i++)
printf("%d%s", A[i], i + 1 < n ? ", " : "\n");
}
with 1.txt as:
4
1
2
3
4
a sample session looks like this:
Enter filename: 1.txt
n = 4
A = 1, 2, 3, 4

Thread 1: EXC_BAD_ACCESS (code=1, address=0x68 [duplicate]

I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}

Reading a matrix from file in C

I want to read the matrix from file and store it in an array. But the array is storing only the last value of matrix. Can anyone explain this please?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp, *fp1;
int n = 0, i, j, a[4][4], b[16];
fp = fopen("Output.txt", "r");
if (fp == NULL) {
printf("\nError; Cannot open file");
exit(1);
}
while (!feof(fp)) {
i = 0;
fscanf(fp, "%d", &n);//reads the file containing matrix
b[i] = n;//this part is not working
printf("%d\n", n);
i++;
}
fclose(fp);
fp1 = fopen("Output2.txt", "w");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
fprintf(fp1, "%d\t", a[i][j] * 2);
}
fprintf(fp1, "\n");//creates file of altered matrix
}
fclose(fp1);
return 0;
}
Your input loop is incorrect:
you reset i to 0 at the beginning of each iteration
you use an incorrect test: while (!feof(fp)). Learn here why: Why is “while ( !feof (file) )” always wrong? . You should instead test the array index against the array length and check if fscanf() succeeds at reading the next value.
Here is a corrected version:
for (i = 0; i < 16; i++) {
if (fscanf(fp,"%d",&n) != 1) { //reads the file containing matrix
fprintf(stderr, "invalid input\n");
exit(1);
}
b[i] = n;
printf("%d\n", n);
}
Note also that you do not read the values into the 2D matrix, so the output loop has undefined behavior because a is uninitialized.
Here is a improved version:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
int i, j, a[4][4];
fp = fopen("Output.txt", "r");
if (fp == NULL) {
fprintf(stderr, "Error: Cannot open file Output.txt for reading\n");
exit(1);
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (fscanf(fp, "%d", &a[i][j]) != 1) {
fprintf(stderr, "invalid input for a[%d][%d]\n", i, j);
fclose(fp);
exit(1);
}
}
}
fclose(fp);
fp1 = fopen("Output2.txt", "w");
if (fp1 == NULL) {
fprintf(stderr, "Error: Cannot open file Output2.txt for writing\n");
exit(1);
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
fprintf(fp1, "%d\t", a[i][j] * 2);
}
fprintf(fp1, "\n");
}
fclose(fp1);
return 0;
}

fscanf not reading from a file containing asterisk characters

I tried to read a file containing an empty box of '*', the error message doesn't get printed, so the file is opened, but the scan doesn't work. I tried to print the count variable, and the value of count is 0. I don't really know where the fault is. Please help... Thanks
the file content that I want to read
int openmap(int file_no){
char filename[32];
char mapp[100][100];
int number;
int count;
int x[100];
int nomor = 1;
for(int i = 1; i <= file_no; i++){
sprintf(filename, "map%d.txt", i);
FILE *test = fopen(filename,"r");
if(test)
{
printf("%2d. Map %d\n", nomor, i);
x[nomor-1] = i;
nomor++;
fclose(test);
}else if(!test && i > file_no){
printf("No map available!");
return 1;
}
}
do{
printf("[0 to cancel] [1 - %d]>> ", nomor-1);
scanf("%d", &number);
}while(number < 0 || number > file_no);
if(number > 0){
sprintf(filename,"map%d.txt", x[number-1]);
printf("%s", filename);
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(int i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
}
I created a small test program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main () {
char mapp[100][100];
int i, count = 0;
char filename[32];
sprintf(filename, "test.txt");
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof(open)){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
as far as i can see the only issue you have regarding the relevant section is your while loop condition, you should use: while(!feof(open)) - i tested my solution and it works so it seems that this is the only issue in your solution

Error when trying to read in numbers from txt file in C

I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}

Resources